1. 背景
双指针解决链表相关的问题,基本都是中等难度
- 删除链表的倒数第 N 个结点
- 旋转链表
2. 方案
leetcode 19
ini
public ListNode removeNthFromEnd(ListNode head, int n){
ListNode second = head;
ListNode first = head;
for (int i = 0; i < n; i++) {
first = first.next;
}
if (first == null){
return head.next;
}
while(first.next != null){
first = first.next;
second = second.next;
}
second.next = second.next.next;
return head;
}
leetcode 61
ini
public ListNode rotateRight(ListNode head, int k){
if (head == null || head.next == null){
return head;
}
ListNode temp = head;
int lens = 1;
while (temp.next != null){
lens ++;
temp = temp.next;
}
k = k % lens;
ListNode first = head;
ListNode second = head;
int idx = 0;
while(first.next != null){
if (idx ++ < k){
first = first.next;
} else {
first = first.next;
second = second.next;
}
}
first.next = head;
head = second.next;
second.next = null;
return head;
}