LeetCode-------reverse-nodes-in-k-group

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-------reverse-nodes-in-k-group相关的知识,希望对你有一定的参考价值。

题目:

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

该题目的意思就是给定一个单链表,将这个单链表每k个元素进行反转,其中不满k个的节点不反转。代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode reverseKGroup(ListNode head, int k) {
14     /*
15     下面这个判断很好理解吧?我就不解释了
16     */
17         if(head == null || k < 2)
18         {
19             return head;
20         }
21     /*
22     老样子,生成一个新节点,用于指向一个新的链表
23     */
24         ListNode pHead = new ListNode(0);
25         pHead.next = head;
26         int count = 0;
27         ListNode node = head;
28         ListNode init = pHead;//初始位置指向生成的新链表的头结点。
29         ListNode currentTail = head;//currentTail节点指向反转后的尾部节点。(其实这个很好理解,就是这个节点始终指向这k个节点的第一个节点,反转后,该第一个节点在后面)
30         ListNode currentHead = head;//该节点用于指向反转后的头部节点(反转后该节点指向的位置为反转前第k个节点)
31         ListNode postNode = null;//定义一个中间节点
32         while(node != null)
33         {
34             count++;
35             node = node.next;
36             if(count == k)//当找到第k个节点
37             {
38         /* 
39         如下的while循环就是这k个节点的反转操作,
40         */
41                 ListNode temp = currentTail.next;
42                 while(temp != node)
43                 {
44                     postNode = currentHead;
45                     currentHead = temp;
46                     temp = temp.next;
47                     currentHead.next = postNode;
48                 }
49         /*
50         
51         */
52                 init.next = currentHead;
53                 init = currentTail;
54                 currentHead = node;//此时node指向第k个节点的下一个节点
55                 currentTail = node;
56                 count = 0;//将count的值归零,开始进行下次k个节点的反转。
57             }
58         }
59         init.next = currentHead;//将剩余的节点连接到生成的新链表中。
60         return pHead.next;//返回这个这个生成的新链表 
61     }
62 }

本题主要的核心点就是在对这k个节点的反序操作。


以上是关于LeetCode-------reverse-nodes-in-k-group的主要内容,如果未能解决你的问题,请参考以下文章