Topic:
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, and only nodes itself is 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
Ideas:
There's no clue, it's a pointer exchange.
Packagelist; Public classReversenodesinkgroup { PublicListNode Reversekgroup (ListNode head,intk) {if(Head = =NULL|| K < 2)returnHead; ListNode First=NewListNode (0); First.next=Head; ListNode PREVP=First ; ListNode P=Head; ListNode Q=p; while(Q! =NULL) { inti = 0; for(; Q! =NULL&& i < k-1; ++i) {q=Q.next; } if(i = = k-1 && Q! =NULL) {ListNode Qnext=Q.next; Q.next=NULL; ListNode Newhead=reverselist (P); Prevp.next=Newhead; PREVP=p; P=Qnext; Q=Qnext; Prevp.next=Qnext; } } returnFirst.next; } //This function is only being invoked when the list contains more than one node. PrivateListNode reverselist (ListNode head) {ListNode PREVP=NULL; ListNode P=Head; ListNode Q=Head.next; while(P! =NULL&& Q! =NULL) {ListNode tmp=Q.next; Q.next=p; P.next=PREVP; PREVP=p; P=Q; Q=tmp; } returnp; } Public Static voidMain (string[] args) {//TODO auto-generated Method StubListNode A1 =NewListNode (1); ListNode A2=NewListNode (2); ListNode A3=NewListNode (3); ListNode A4=NewListNode (4); ListNode A5=NewListNode (5); A1.next=A2; A2.next=A3; A3.next=A4; A4.next=A5; A5.next=NULL; Reversenodesinkgroup R=NewReversenodesinkgroup (); ListNode x= R.reversekgroup (A1, 3); while(X! =NULL) {System.out.println (x.val); X=X.next; } }}
Leetcode-reverse Nodes in K-group