25. Reverse Nodes in k-Group(链表k-组反转)

问题描述
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked 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->3->4->5;当k=2时,则每2个节点顺序翻转:2->1->4->3->5;当k=3时,每3个节点顺序反转:3->2->1->4->5。
所以我们的思路可以分为两部分:首先将原链表每k个节点就划分;然后在k个节点内部进行顺序发展。具体过程可见代码:

代码展示

#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;

struct ListNode {                                      //定义链表的结构体 
      int val;
      ListNode*next;
      ListNode(int x) : val(x), next(NULL) {}
 };

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k){
    ListNode*curr;
    curr = head;
    int count = 0;
    while(curr != NULL && count != k){              //从头节点开始往后找到k个节点 
        curr = curr->next;
        count++;
    }
    if (count == k) {                          //如果有k个节点则进行这k个节点的谁顺序变换 
        curr = reverseKGroup(curr, k);         //从k+1节点开始,重复上过程,查找第2个k个节点 
        while (count-- > 0) { 
            ListNode*tmp = head->next;         //定义节点tmp为头结点的下一个节点 
            head->next = curr;                 //使原头结点指向指向k+2节点的节点。 
            curr = head;                       //让curr表示原来的头结点 
            head = tmp;                        //此时移动头结点,使原来的第二节点变为新的头结点 
        }                                      //经过一轮循环,完成了将头结点移出到另一条链表线,原第二节点变为新的头结点 
        head = curr;
    }
    return head;
}
}; 

int main(){
    cout<<"输入链表的长度:"; 
    int n;
    cin>>n;; 
    ListNode* head=NULL;
    ListNode* p;
    int a;
    for(int i=0;i<n;i++){
        cin>>a;
        if (head == NULL){
            head = (ListNode *)malloc(sizeof(ListNode));
            head->val = a;
            p = head;
        }
        else{
        p->next = (ListNode *)malloc(sizeof(ListNode));
        p = p->next;
        p->val = a;
        }
    }
    p->next=NULL;
    Solution solution;
    cout<<"输入你想要反转的长度:";
    int b; 
    cin>>b;
    ListNode* result = solution.reverseKGroup(head, b);
    while(result!=NULL){
        cout<<result->val<<" "; 
        result=result->next;
    }
    cout<<endl;
    return 0;
} 

运行结果展示
这里写图片描述

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值