leetcode刷题记录 3



Remove Nth Node From End of List

思路:

快慢指针,慢指针找到倒数第n个前一个结点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/

public class {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fast = head;
ListNode slow = head;

for (int i = 0; i < n; i++) {
fast = fast.next;
}

if (fast == null) {
return head.next;
}

while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;

return head;
}
}


Swap Nodes in Pairs

思路:

交换两个节点等价于交换两个节点的val

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/

public class {
public ListNode swapPairs(ListNode head) {
ListNode p = head;
while (p != null && p.next != null) {
int temp = p.val;
p.val = p.next.val;
p.next.val = temp;
p = p.next.next;
}
return head;
}
}


Rotate List

思路:

解法一:

  1. 求链表长度len
  2. k%len取模
  3. 快慢指针定位
  4. 交换指针

解法二:
把整个链表连成环,找到切点再分割

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/

public class {
public ListNode rotateRight(ListNode head, int k) {
if(head == null)
return head;

ListNode fakeHead = new ListNode(0);
fakeHead.next = head;
ListNode fast = fakeHead;
ListNode slow = fakeHead;

int len = 0;
ListNode p = head;
while(p != null) {
p = p.next;
len++;
}

k = k % len;

for(int i = 0; i < k; i++) {
fast = fast.next;
}
while(fast.next != null) {
fast = fast.next;
slow = slow.next;
}
fast.next = head;
fakeHead.next = slow.next;
slow.next = null;

return fakeHead.next;
}
}