Reverse Nodes in k-Group
发布日期:2021-10-24 14:20:25 浏览次数:5 分类:技术文章

本文共 2761 字,大约阅读时间需要 9 分钟。

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

其中,创建了一个dump充当头结点,使得操作统一。使用pre来记录要逆转的序列的前面一个结点,而q记录要逆转序列之后的一个结点,每次逆转返回逆转之后的最后一个元素,也就是下一次逆转的前驱。

 

C++代码实现:

#include
#include
#include
#include
using namespace std;//Definition for singly-linked list.struct ListNode{ int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};class Solution{public: ListNode *reverseKGroup(ListNode *head, int k) { if(head==NULL||head->next==NULL) return head; int len=0; ListNode *p=head; ListNode *q=NULL; ListNode *pre=NULL; while(p) { len++; p=p->next; } ListNode *dump=new ListNode(0); dump->next=head; pre=dump; p=head; int count=0; while(p) { count++; q=p->next; while(count==k) { pre=reverse(pre,q); count=0; } p=q; } return dump->next; } ListNode *reverse(ListNode *pre,ListNode *q) { if(pre->next==NULL) return NULL; if(pre->next->next==NULL) return pre->next; ListNode *p=pre->next; ListNode *pp=NULL; ListNode *temp=NULL; pp=p->next; p->next=NULL; while(pp!=q) { temp=pp; pp=pp->next; temp->next=NULL; temp->next=pre->next; pre->next=temp; } p->next=q; pre=p; return pre; } void createList(ListNode *&head) { ListNode *p=NULL; int i=0; int arr[10]= {
9,8,7,6,5,4,3,2,1,0}; for(i=0; i<10; i++) { if(head==NULL) { head=new ListNode(arr[i]); if(head==NULL) return; } else { p=new ListNode(arr[i]); p->next=head; head=p; } } }};int main(){ Solution s; ListNode *L=NULL; s.createList(L); ListNode *head=L; while(head) { cout<
val<<" "; head=head->next; } cout<
val<<" "; head=head->next; } cout<

运行结果:

转载于:https://www.cnblogs.com/wuchanming/p/4117635.html

转载地址:https://blog.csdn.net/weixin_30791095/article/details/97950218 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:css3动画效果
下一篇:创建ASP.NET Webservice

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年03月30日 04时09分46秒