LeetCode | Reverse Nodes in k-Group

100 篇文章 0 订阅
13 篇文章 0 订阅

链表的反转
写的是生无可恋啊…
我的思路….其实和正确答案都差不多,但是一直ce调不出来…

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

错误的代码就不贴了,然后这个是在本地测试的,找了好久找一个bug找不到orz
注意本地建立链表和输出链表的方式~

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h> 
#include<string.h>
#include<stdlib.h>
#include<vector>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

/**
建立一个链表 
**/ 
ListNode* initNode(vector<int> arr){
    ListNode root(-1);
    root.next = NULL;
    ListNode* end = &root;
    int n = arr.size();
    for (int i = 0; i < n; i++){
        end->next = new ListNode(arr[i]);
        end = end->next;
    }
    return root.next;
}

/**
输出一个链表 
**/
void outNode(ListNode* head){
    ListNode* temp=head;
    int count = 0;
    while (temp != NULL){
        printf("%d ", temp->val);
        temp = temp->next;
    }
    printf("\n");
}

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(head==NULL || head->next==NULL || k<2) return head;
        ListNode root(-1);
        root.next = head;

        for(ListNode *p=&root,*end=head;end;end=p->next){
            //一次性寻找k-1个节点,从第一个节点出发
            for(int i=1;i<k&&end!=NULL;i++)
            end=end->next;

            if(end==NULL) break;

            p=reverse(p,p->next,end);
        }

        return root.next;
    }

    //对从begin到end的链表进行反转...
    ListNode* reverse(ListNode* preNode,ListNode* begin,ListNode* end){
        //末尾之后的
        ListNode* end_next=end->next;
        //注意这里的三指针用法
        //这也非常值得记忆和推敲
        for(ListNode *p=begin,*cur=p->next,*next=cur->next;
            cur != end_next;
            p=cur,cur=next,next=next?next->next:NULL){
                cur->next=p;
        }
        begin->next=end_next;
        preNode->next=end;
        return begin;
    }
};

int main(){
    //输入所有数据
    int a[] = { 1, 2, 3, 4, 5 };
    int k = 3;
    //将数组转化为vector ,5表示数组长度 
    vector<int> v(a, a + 5);
    ListNode *head = initNode(v);
    Solution solution;
    head=solution.reverseKGroup(head, k);
    outNode(head);
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值