码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Reverse Nodes in k-Group

时间:2014-12-01 22:32:51      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:算法   leetcode   

问题描述:

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


基本思路:

本题思路是很简单的。先求出链表长度,对每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

标签:算法   leetcode   

原文地址:http://blog.csdn.net/chenlei0630/article/details/41653035

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!