leetcode_25_Reverse Nodes in k-Group

来源:互联网 发布:windows nginx 下载 编辑:程序博客网 时间:2024/05/01 02:57

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢微笑


Reverse Nodes in k-Grou

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


class Solution {//once the link order of the list is changed, //we must keep the previous pointer(p in the code) updated, if we want to use it agianpublic:void reverse_range(ListNode* prev, ListNode* end, ListNode*& p){ListNode* last = prev->next;ListNode* cur = last->next;while(cur != end){last->next = cur->next;cur->next = prev->next;prev->next = cur;cur = last->next;}p = last;}ListNode *reverseKGroup(ListNode *head, int k) {if(k <= 1) return head;ListNode *dummy = new ListNode(-1);dummy->next = head;ListNode* prev = dummy;ListNode* p = dummy->next;int cnt = 1;while(p != NULL){if(cnt%k == 0){reverse_range(prev, p->next, p);//update p is very importantprev = p;}p = p->next;cnt++;}return dummy->next;}};


#include<iostream>using namespace std;#define N 5struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};class Solution {//once the link order of the list is changed, //we must keep the previous pointer(p in the code) updated, if we want to use it agianpublic:void reverse_range(ListNode* prev, ListNode* end, ListNode*& p){ListNode* last = prev->next;ListNode* cur = last->next;while(cur != end){last->next = cur->next;cur->next = prev->next;prev->next = cur;cur = last->next;}p = last;}ListNode *reverseKGroup(ListNode *head, int k) {if(k <= 1) return head;ListNode *dummy = new ListNode(-1);dummy->next = head;ListNode* prev = dummy;ListNode* p = dummy->next;int cnt = 1;while(p != NULL){if(cnt%k == 0){reverse_range(prev, p->next, p);//update p is very importantprev = p;}p = p->next;cnt++;}return dummy->next;}};ListNode *creatlist(){ListNode *head = NULL;ListNode *p;for(int i=0; i<N; i++){int a;cin>>a;p = (ListNode*) malloc(sizeof(ListNode));p->val = a;p->next = head;head = p;}return head;}int main(){ListNode *list = creatlist();Solution lin;int a;cin>>a;ListNode *outlist = lin.reverseKGroup ( list,a );for(int i=0; i<N; i++){cout<<outlist->val;outlist = outlist->next;}}


1 0
原创粉丝点击