reverse linkedlist in k group

来源:互联网 发布:淘宝为什么不能付款 编辑:程序博客网 时间:2024/06/04 23:27

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

public class Solution {    public ListNode swapPairs(ListNode head) {        // Start typing your Java solution below        // DO NOT write main() function        if(head==null) return null;        ListNode t=(head.next!=null)?head.next:head;        while(head.next!=null){            ListNode tmp=head.next.next;            head.next.next=head;            if(tmp!=null){ head.next=(tmp.next!=null)?tmp.next:tmp; head=tmp;}            else {head.next=null;                  break;}        }        return t;            }    }

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; *         next = null; *     } * } */public class Solution {    public ListNode reverseKGroup(ListNode head, int k) {        // Start typing your Java solution below        // DO NOT write main() function        if(head==null) return null;        ListNode tmp=head;                int i=1;        while(tmp.next!=null){            i++;            tmp=tmp.next;        }        return reverse( head,  k,  i);                            }        public ListNode reverse(ListNode head, int k, int i){        if(i<k) return head;        ListNode tmp=head;        for(int m=0;m<k;m++)    tmp=tmp.next;        ListNode t=reverse(tmp,k,i-k);        if(head.next!=null) tmp=head.next;        head.next=t;                for(int m=1;m<k;m++){            ListNode tt=head;            head=tmp;            tmp=head.next;            head.next=tt;        }         return head;                    }        }

the k group is a generalized problem for the swap pair problem.

can be done both iteratively or recursively