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.
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
其中,创建了一个dump充当头结点,使得操作统一。使用pre来记录要逆转的序列的前面一个结点,而q记录要逆转序列之后的一个结点,每次逆转返回逆转之后的最后一个元素,也就是下一次逆转的前驱。
C++代码实现:
#include<iostream> #include<new> #include<vector> #include<cmath> using namespace std; //Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *reverseKGroup(ListNode *head, int k) { if(head==NULL||head->next==NULL) return head; int len=0; ListNode *p=head; ListNode *q=NULL; ListNode *pre=NULL; while(p) { len++; p=p->next; } ListNode *dump=new ListNode(0); dump->next=head; pre=dump; p=head; int count=0; while(p) { count++; q=p->next; while(count==k) { pre=reverse(pre,q); count=0; } p=q; } return dump->next; } ListNode *reverse(ListNode *pre,ListNode *q) { if(pre->next==NULL) return NULL; if(pre->next->next==NULL) return pre->next; ListNode *p=pre->next; ListNode *pp=NULL; ListNode *temp=NULL; pp=p->next; p->next=NULL; while(pp!=q) { temp=pp; pp=pp->next; temp->next=NULL; temp->next=pre->next; pre->next=temp; } p->next=q; pre=p; return pre; } void createList(ListNode *&head) { ListNode *p=NULL; int i=0; int arr[10]= {9,8,7,6,5,4,3,2,1,0}; for(i=0; i<10; i++) { if(head==NULL) { head=new ListNode(arr[i]); if(head==NULL) return; } else { p=new ListNode(arr[i]); p->next=head; head=p; } } } }; int main() { Solution s; ListNode *L=NULL; s.createList(L); ListNode *head=L; while(head) { cout<<head->val<<" "; head=head->next; } cout<<endl; L=s.reverseKGroup(L,3); head=L; while(head) { cout<<head->val<<" "; head=head->next; } cout<<endl; }
运行结果: