Reverse Nodes in k-Group

来源:互联网 发布:南大女生碎尸案 知乎 编辑:程序博客网 时间:2024/04/30 10:04

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

解题思路:


0    ->     1     ->    2     ->     3         ->          4        - >         5

pre        first       end(cur)   nextfirst

1、确定上述指针的位置;

2、反转first 到end之间的链表;

3、然后再把pre.next指向end,first.next指向nextfirst,然后移动四个指针的位置。


public ListNode reverseKGroup(ListNode head, int k) {         if(head == null || k == 0 || k == 1) return head;                  ListNode newhead = new ListNode(0);         newhead.next = head;                  ListNode pre = newhead;         ListNode cur = head;         ListNode first = head;         while(cur != null){                          for(int i = 1; i < k && cur != null; i ++){                 cur = cur.next;             }             if(cur == null) break;                          ListNode nextfirst = cur.next;                          ListNode tmp = first;             ListNode afttmp = tmp.next;             tmp.next = null;             while(tmp != cur){                 ListNode next = afttmp.next;                 afttmp.next = tmp;                 tmp = afttmp;                 afttmp = next;             }                             pre.next = cur;             first.next = nextfirst;             pre = first;             first = nextfirst;             cur = nextfirst;                     }                  return newhead.next;             }




1 0