反转链表
206. 反转链表
206. 反转链表

主要是cur的next指向前一个节点。其实这个只是双指针,next指针只是保存下一个节点。
public ListNode reverseList(ListNode head) {
ListNode pre = null, cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
92. 反转链表 II
92. 反转链表 II

思路一:采用206的思路,不过要将子链表切割出来(可以从left开始反转,指向null),反转后在连接。

思路二:采用头插法,pre永久指向7这个节点,curr永久指向2这个节点。
24. 两两交换链表中的节点
思路:采用四指针进行插针引线,不断判断 pre.next != null && pre.next.next != null。
public ListNode swapPairs(ListNode head) {
if(head == null)
return null;
if(head.next == null)
return head;
ListNode dummyHead = new ListNode(-1,head);
ListNode pre = dummyHead;
while(pre.next != null && pre.next.next != null) {
ListNode l1 = pre.next, l2 = l1.next, next = l2.next;
pre.next = l2;
l2.next = l1;
l1.next = next;
pre = l1;
}
return dummyHead.next;
}
25. K 个一组翻转链表
思路:按照92题的思路,可以每隔k个都进行头插法,下一组 g = p; p = p.next; 即可。
public ListNode reverseKGroup(ListNode head, int k) {
if(k == 1)
return head;
// 定义一个dummyHead, 方便处理
ListNode dummyHead = new ListNode(0, head);
int length = 0;
while(head != null) {
length++;
head = head.next;
}
// 初始化指针
ListNode g = dummyHead;
ListNode p = dummyHead.next;
for(int m = 1,n = m + k - 1; n <= length; m = n + 1,n = m + k - 1)
{
// 头插法插入节点
for (int i = 0; i < n - m; i++) {
ListNode removed = p.next;
p.next = p.next.next;
removed.next = g.next;
g.next = removed;
}
g = p;
p = p.next;
}
return dummyHead.next;
}
61. 旋转链表
思路:不需要一个个节点进行旋转。k个一起旋转,相当于拼接两个子串而已(就是头插后面的一个子串,为不是一个个节点进行头插),k大于链表长度,则k = k % length 即可。用到了双指针的滑动窗口。
public ListNode rotateRight(ListNode head, int k) {
if(head == null)
return null;
if(head.next == null)
return head;
ListNode dummyHead = new ListNode(-1,head);
ListNode cur = dummyHead;
int length = 0;
while(cur.next != null) {
cur = cur.next;
length++;
}
k = k % length;
ListNode front = dummyHead, tail = front;
for(int i = 0; i < k; i++)
tail = tail.next;
while(tail.next!=null) {
tail = tail.next;
front = front.next;
}
tail.next = dummyHead.next;
dummyHead.next = front.next;
front.next = null;
return dummyHead.next;
}
6104

被折叠的 条评论
为什么被折叠?



