LeetCode-Reverse Nodes in k-Group

本文介绍了一种链表操作算法——K组翻转。该算法将链表按K个节点一组进行翻转,并详细展示了具体的实现过程及核心代码。通过对链表节点的巧妙调整,实现了仅使用常数内存完成翻转任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 

源码:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 ListNode *reverse(ListNode *head,ListNode *last_tail){ 
 5       ListNode *next_node=head->next;
 6       ListNode *res=head;
 7       
 8       while(next_node){
 9             ListNode *tmp=next_node->next;
10             next_node->next=head;
11             head=next_node;
12             next_node=tmp;
13       }
14       
15       last_tail->next=head;
16       return res;
17 }
18 
19 ListNode* reversekGroup(ListNode *head,int k){
20      ListNode *newHead=new ListNode(0);
21      newHead->next=head;
22      
23      int cnt=0;
24      ListNode *cur_node=head;
25      ListNode *last_tail=newHead;
26      while(cur_node){
27            cnt++;
28            if(cnt==k){
29                 ListNode *tmp=cur_node->next;
30                 cur_node->next=0;
31                 
32                 last_tail=reverse(last_tail->next,last_tail);
33                 last_tail->next=tmp;
34                 
35                 cnt=0;
36                 continue;
37            }
38            cur_node=cur_node->next;
39      }
40      return newHead->next;
41 }

 

 

 

转载于:https://www.cnblogs.com/sixue/p/4014594.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值