LeetCode -- Reverse Nodes in K-Group
Question:
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
Analysis:
这是Swap Nodes的升级版本,将链表中的节点分为K组,每组中的节点顺序倒置,但组之间的顺序不变,如果剩余节点个数不足k个,则不颠倒。
思路是:首先生成一个头结点,防止找不到颠倒后的链首。然后设置三个节点,一个start,指向下一段链表的链首;一个p,指向本组链表的链首;一个q,寻找本组链表的结尾;一个val,指示目前本组已经遍历过几个节点。同时在整个程序中需要一个全局指针,便于寻找最终返回链表的链尾。这样,p指向的本组链表只需调用函数就地颠倒即可,然后加入返回链的链尾。
Answer:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { private ListNode tail; public ListNode reverseKGroup(ListNode head, int k) { if(head == null || head.next == null) return head; if(k <= 1) return head; //创建一个首节点 ListNode h = new ListNode(-1); tail = h; ListNode start = head, p = head, q = head; //start指向目前要颠倒结点的链首,q遍历结点找到k个结点 while(q != null || q.next != null) { int val = 1; while(val < k && q.next != null) { q = q.next; val ++; } if(val < k && q.next == null) { tail = getTail(); tail.next = start; return h.next; } start = q.next; q.next = null; ListNode jion = reverseList(p); tail = getTail(); tail.next = jion; if(start == null) { return h.next; } p = start; q = start; } return h.next; } public ListNode getTail() { while(tail.next != null) tail = tail.next; return tail; } public ListNode reverseList(ListNode head) { if(head == null || head.next == null) return head; ListNode h = head; while(head.next != null) { ListNode p = head.next; head.next = p.next; p.next = h; h = p; } return h; } }
You are here!
Your runtime beats 98.99% of java submissions.
(哈哈,感觉链表题目差不多OK了,可以不用看别人的思路,最终runtime也会大于98%以上,好有成就感~但是树,图等其他数据结构的还很差,要多练练!)