My code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || k <= 1)
return head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode preTail = dummy;
ListNode tail = head;
ListNode tempHead = head;
int counter = 0;
while (tail != null) {
counter++;
if (counter >= k) {
ListNode temp = tail.next;
/** reverse this part of list */
tail.next = null;
reverse(tempHead);
tempHead.next = temp;
preTail.next = tail;
preTail = tempHead;
tempHead= temp;
tail = temp;
counter = 0;
}
else {
tail = tail.next;
}
}
return dummy.next;
}
/** reverse the whole linked list */
private void reverse(ListNode head) {
if (head.next == null)
return;
ListNode next = head.next;
ListNode pre = head;
while (next != null) {
ListNode temp = next;
next = next.next;
temp.next = pre;
pre = temp;
}
head.next = null;
}
public static void main(String[] args) {
Solution test = new Solution();
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(4);
n1.next = n2;
n2.next = n3;
n3.next = n4;
ListNode head = test.reverseKGroup(n1, 2);
while (head != null) {
System.out.println(head.val);
head = head.next;
}
}
}
这道题木自己做了出来,虽然期间用eclipse debug了一次,找出了错误。
思路是对的。设计一个计数器。然后走到固定点。
保存后面结点,切断它与后面结点的联系,然后reverse
然后和后面结点在接起来。继续遍历。
烦的是。下一次,当我翻转下一个链表时,得到的新头结点,需要更新,紧跟在上一个链表的尾结点之后。所以需要 preTail
还有要记录下每一个子链表的头, 所以需要 tempHead
这道题木难度还好,就是烦一些。
Anyway, Good luck, Richardo!
My code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
ListNode curr = head;
int counter = 0;
while (curr != null) {
counter++;
if (counter < k) {
curr = curr.next;
}
else {
ListNode next = curr.next;
ListNode tempHead = pre.next;
curr.next = null;
pre.next = reverse(tempHead);
tempHead.next = next;
pre = tempHead;
curr = next;
counter = 0;
}
}
return dummy.next;
}
private ListNode reverse(ListNode head) {
ListNode pre = head;
ListNode curr = pre.next;
while (curr != null) {
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
head.next = null;
return pre;
}
}
并不是很难。
Anyway, Good luck, Richardo! -- 09/22/2016