【Leetcode】【Hard】Reverse Nodes in k-Group

本文介绍了一种算法,该算法将链表中的节点每K个一组进行反转,并返回修改后的链表。讨论了当节点数不是K的倍数时的处理方式,并提供了具体的实现代码。

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个结点,剩余结点不变;如果不够K个结点,则保持原链表。

之后循环调用此函数。

 

代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* reverseKGroup(ListNode* head, int k) {
12         if (head == NULL || head->next == NULL || k == 1)
13             return head;
14         ListNode* newhead = new ListNode(0);
15         ListNode* newlist = newhead;
16         ListNode* curNode = head;
17         while (curNode != NULL) {
18             newlist->next = reverseListKNodes(curNode, k);
19             // After "reverseListKNodes" func, "curNode" will be the end of reversed sublist
20             newlist = curNode;
21             curNode = curNode->next;
22         }
23         
24         head = newhead->next;
25         delete newhead;
26         return head;
27     }
28     
29     ListNode* reverseListKNodes(ListNode* sub_head, int k) {
30         if (sub_head == NULL || sub_head->next == NULL)
31             return sub_head;
32             
33         ListNode* newhead = NULL;
34         ListNode* nodesleft = sub_head;
35         ListNode* curNode = NULL;
36         
37         for (int i = 0; i < k; ++i) {
38             if (nodesleft == NULL)
39                 return reverseListKNodes(newhead, i);
40             curNode = nodesleft;
41             nodesleft = nodesleft->next;
42             curNode->next = newhead;
43             newhead = curNode;
44         }
45         
46         sub_head->next = nodesleft;
47         return newhead;
48     }
49 };

 

转载于:https://www.cnblogs.com/huxiao-tee/p/4592818.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值