Reverse Nodes in k-Group

来源:互联网 发布:广东联合数据科技服务 编辑:程序博客网 时间:2024/06/06 09:39

题目描述:
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

这个题算是非常考验细节的了,要每一步都考虑清楚,也要注意代码的简洁。

public ListNode reverseKGroup(ListNode head, int k) {     if(head==null || k==1) return head;      //start记下每一组的开始    ListNode start = new ListNode(0);      start.next = head;      ListNode pre = null;      ListNode cur = head;      ListNode next = null;      ListNode end = null;      head = start;      while( cur != null) {                    int i=k;          end = cur;          while(--i>0 && end != null ){              end = end.next;          }          if(end==null) return head.next;           i=k;          while(i-->0) {              next = cur.next;              cur.next = pre;              pre = cur;              cur = next;          }          start.next.next = cur;          ListNode t = start.next;          start.next = pre;          start = t;      }        return head.next;  }  
0 0
原创粉丝点击