首页 > 代码库 > [leetcode]Reverse Nodes in k-Group

[leetcode]Reverse Nodes in k-Group

问题描述:

Given a linked list, reverse the nodes of a linked listk 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


基本思路:

本题思路是很简单的。先求出链表长度,对每k个进行反转,如果剩下的不足k个则不做反转。

本题容易产生的问题是指针之间的各个指向容易出错。


代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {  //Java
    public ListNode reverse(ListNode head,int n)  
	  {
		ListNode   tmp = head;
		int step = 1;
		tmp = tmp.next;
		ListNode tmphead = head;
		ListNode p = null;
		while(step < n){
			 p = tmp.next;
			tmp.next = head;
			head = tmp;
			tmp = p;
			step++;
		}
		tmphead.next = p;
		return head;
	  }
	  public ListNode reverseKGroup(ListNode head, int k) {
        if(k <=1)
        	return head;
        
        int size = 0;
        ListNode tmp = head;
        while(tmp != null){
        	size++;
        	tmp =tmp.next;
        }
        if(size < k)
        	return head;
        
        ListNode newhead = new ListNode(0);
        newhead.next = head;
        ListNode result = newhead;
		 
        tmp = newhead.next;
        ListNode tmphead = newhead;
        ListNode tmptail = newhead;
        while(size >= k){
        	tmphead = reverse(tmp, k);
        	tmptail.next = tmphead;
        	tmptail = tmp;
        	tmp = tmp.next;
        	tmptail.next = null;
        	size -=k;
        }
		  
        if(size > 0)
        	tmptail.next = tmp;
        return newhead.next;
		  
    }
	  

	  
}


[leetcode]Reverse Nodes in k-Group