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. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseKGroup(ListNode head, int k) { ListNode s,p=new ListNode(0); p.next=head;head=p;s=p; int len=k; while(k-->0 && s!=null)s=s.next; while(s!=null){ ListNode tmp,l=p.next,flag=s.next,tail=p.next; p.next=null; while(l!=flag){ tmp=p.next; p.next=l; l=l.next; p.next.next=tmp; } tail.next=l; p=tail; s=tail; k=len; while(k-->0 && s!=null)s=s.next; } return head.next; } }
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ void reverse(struct ListNode** p,struct ListNode **s){ struct ListNode *l=(*p)->next,*tmp,*tail=(*p)->next,*flag=(*s)->next; (*p)->next=NULL; while(l!=flag){ tmp=(*p)->next; (*p)->next=l; l=l->next; (*p)->next->next=tmp; } tail->next=l; *p=tail; *s=tail; } struct ListNode* reverseKGroup(struct ListNode* head, int k) { struct ListNode *s,*p=(struct ListNode*)malloc(sizeof(struct ListNode)); int len=k; p->next=head; head=p;s=p; while(k-- && s!=NULL)s=s->next; while(s!=NULL){ reverse(&p,&s); k=len; while(k-- && s!=NULL)s=s->next; } return head->next; }
/** * 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) { ListNode *s,*p=(ListNode*)malloc(sizeof(ListNode)); int len=k; p->next=head;head=p;s=p; while(k-- && s!=NULL)s=s->next; while(s!=NULL){ reverse(p,s); k=len; while(k-- && s!=NULL)s=s->next; } return head->next; } private: void reverse(ListNode* &p,ListNode* &s){ ListNode *tmp,*tail=p->next,*flag=s->next,*l=p->next; p->next=NULL; while(l!=flag){ tmp=p->next; p->next=l; l=l->next; p->next->next=tmp; } tail->next=l; p=tail; s=tail; } };
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @param {integer} k # @return {ListNode} def reverseKGroup(self, head, k): p=ListNode(0) p.next=head;head=p;s=p len=k while k>0 and s!=None:k-=1;s=s.next while s!=None: flag=s.next;tail=p.next;l=p.next while l!=flag: tmp=p.next p.next=l l=l.next p.next.next=tmp tail.next=l p=tail;s=tail k=len while k>0 and s!=None:k-=1;s=s.next return head.next
LeetCode 25 Reverse Nodes in k-Group (C,C++,Java,Python)
原文地址:http://blog.csdn.net/runningtortoises/article/details/45647795