[Linked List]Reverse Nodes in k-Group
Total Accepted: 48614 Total Submissions: 185356 Difficulty: Hard
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
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* newHead=NULL,*p=head,*next=NULL; while(p){ next = p->next; p->next = newHead; newHead = p; p = next; } return newHead; } ListNode* reverseKGroup(ListNode* head, int k) { if(k<=1){ return head; } ListNode *pre=NULL,*next=NULL; ListNode *cur=head; ListNode *reverseHead = NULL; int cnt = 0; while(cur){ if(cnt==0){ reverseHead = cur; } next = cur->next; ++cnt; if(cnt==k){ cur->next=NULL; ListNode *newHead = reverseList(reverseHead); pre ? pre->next = newHead : head=newHead; reverseHead->next = next; pre = reverseHead; cur = next; cnt = 0; }else{ cur = cur->next; } } return head; } };
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记