LeetCode -- Rotate List
2015-11-07 18:25
344 查看
题目描述:
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
实现代码:
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; } }
相关文章推荐
- Maven之—— 打包编译出现File encoding has not been set问题
- LeetCode -- Roman to Integer
- centos+scala2.11.4+hadoop2.3+spark1.3.1环境搭建
- UVa1587 Box(排序)
- Android 计时器 Chronometer的简单实用
- http响应报文
- Spring ConnectionHolder
- iOS常用的几种设计模式
- 使用git来打包Android源码
- HTTP响应码摘自apach官网
- LeetCode -- Repeated DNA Sequences
- 值得你关注的Android6.0上的重要变化(一)
- JPA乐观锁
- 归并排序
- LeetCode -- Number of Islands
- 烂泥:haproxy学习之手机规则匹配
- SpringMVC+Spring+MyBatis配置
- 通过“改变引用”和“加锁”的方式提高缓存访问并发度
- service服务、电话录音
- 详解宏定义(#define)