Reverse Nodes in k-Group (Java)

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

因爲此題中的鏈表重建方法有一定的重複性,所以把需要修改的地方設置爲方法調用。

Source

    public ListNode reverseKGroup(ListNode head, int k) {
    	if(head == null || k == 1)
    		return head;
    	if(head.next == null) return head;
    	
    	ListNode p = new ListNode(0);
    	ListNode pre = p;
    	pre.next = head;
    	ListNode cur = pre;
    	int cnt = 0;
    	while(cur != null){
    		cnt ++;
    		cur = cur.next;
    		if(cur == null) break;
    		if(cnt == k){
    			ListNode next = cur.next;
    			pre = reverse(pre, next);
    			cur = pre;
    			cnt = 0;
    		}
    	}
    	return p.next;
    }
    
    public ListNode reverse(ListNode pre, ListNode next){
    	ListNode a = pre.next;
    	ListNode b = a.next;
    	ListNode temp = b.next;
    	ListNode last = a;
    	
    	while(b != next){ //***
    		b.next = a;
    		a = b;
    		b = temp;
    		if(b != null) temp = b.next;
    	}
    	pre.next = a;
    	last.next = next;
    	pre = last;
    	return pre;
    }


Test

    public static void main(String[] args){
    	ListNode p = new ListNode(1);
    	p.next = new ListNode(2);
    //	p.next.next = new ListNode(3);
    //	p.next.next.next = new ListNode(4);
    //	p.next.next.next.next = new ListNode(5);
    	
    	ListNode q = new Solution().reverseKGroup(p, 2);
    	
    	while(q != null){
    		System.out.println(q.val);
    		q = q.next;
    	}
    }	




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章