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

LeetCode -- Rotate List

时间:2015-11-08 15:22:50      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:


Given a list, rotate the list to the right by k places, where k is non-negative.


For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.


就是将倒数K个节点放在链表前。


思路:
1. 遍历链表判断长度len是否小于k,如果是,则k = k % len
2. 如果len = k或len < 2或k < 1,直接返回
3. 遍历链表,移动len - k - 1个位置,存当前位置为q
4. 将q之后的节点存入stack
5. 遍历stack,依次将节点设为头结点
6. 最后,将q.next指向Null


实现代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode RotateRight(ListNode head, int k) 
    {
        if(head == null){
    		return null;
    	}
        var len = LenOf(head);
    	if(len < 2 || k == len || k < 1){
    		return head;
    	}
    	if(k > len){
    		k = k % len;
    	}
    	
    	var stack = new Stack<int>();
    	var p = head;
    	
    	for(var i = 0;i < len - k - 1;i ++){
    		p = p.next;
    	}
    	
    	var q = p;
    	
    	p = p.next;
    	while(p != null){
    		stack.Push(p.val);
    		p = p.next;
    	}
    	q.next = null;
    	
    	while(stack.Count > 0)
    	{
    		var n = new ListNode(stack.Pop());
    		n.next = head;
    		head = n;
    	}
    	
    	return head;
    }


private int LenOf(ListNode head)
{
	var p = head;
	var len = 0;
	while(p != null){
		len ++;
		p = p.next;
	}
	return len;
}
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode -- Rotate List

标签:

原文地址:http://blog.csdn.net/lan_liang/article/details/49704129

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