25. Reverse Nodes in k-Group[hard]

来源:互联网 发布:域名停放 编辑:程序博客网 时间:2024/05/02 04:24

题目:

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

Java

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode reverseKGroup(ListNode head, int k) {        ListNode p = head; int len=0;        while(p!=null){            len++;            p = p.next;        }        int section = len/k;        if(section==0||k==1) return head;        else{            ListNode dummy = new ListNode(0); dummy.next = head;             ListNode duphead = dummy, pre = head, cur = head.next;             for(int i=2;i<=section*k;i++){                if(i%k==1) {duphead = pre;pre = cur; cur = cur.next;}                else{                    pre.next = cur.next;                    cur.next = duphead.next;                    duphead.next = cur;                    cur = pre.next;                }            }            return dummy.next;        }    }}

Python

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def reverseKGroup(self, head, k):        """        :type head: ListNode        :type k: int        :rtype: ListNode        """        if head==None or head.next==None or k==1: return head;        dumy=ListNode(0); pre=ListNode(0); dumy.next=head; pre.next=head;end=pre;        time=True        while end.next!=None:            jumpout=False            for i in range(k):                if end.next == None:                    jumpout=True                    break                end = end.next            if jumpout:                    break            temp=pre.next            self.reverse(pre,end)            end = temp            if time:                dumy.next=pre.next            pre = end            time=False        return dumy.next            def reverse(self,pre,end):        tail=end.next        t=pre.next        c=t.next        while c!=tail :             t.next=c.next            c.next=pre.next            pre.next=c            c=t.next


0 0
原创粉丝点击