Rotate List
来源:互联网 发布:奇妙pk10软件免费版 编辑:程序博客网 时间:2024/05/17 09:33
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
andk = 2
,
return 4->5->1->2->3->NULL
.
题意:将链表末尾的K个数字移到链表首
思路:
1.首先链表长度为n,由于k可能大于n,所以k = k % n;
2.找出需要断开的节点,通过首尾指针之间的间隔(尾指针—头指针 = k)遍历一遍链表即可找出,当尾指针到尾部,头指针就是我们新链表的头部
(一定要记得断开,node.next = null)
3.将原链表的尾部与原链表的头部相连
代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public static ListNode rotate(ListNode head, int n){if(n == 0)return head;ListNode frontNode = head, rearNode = head;int front = 1,rear = 1;while(rearNode != null){if(rear - front != n){rearNode = rearNode.next;rear++;}else{frontNode = frontNode.next;rearNode = rearNode.next;front++;rear++;}}ListNode head1 = frontNode, p = head1;while(p.next != null){p = p.next;}p.next = head;//断开原来的连接while(head.next != head1)head = head.next;head.next = null;return head1;}public static ListNode rotateRight(ListNode head, int n) {if(head == null || head.next == null)return head;int length = 0;ListNode tmp = head;while(tmp != null){length++;tmp = tmp.next;}n = n % length;head = rotate(head, n);return head; }}
0 0
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- rotate-list
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Linux下用C语言调用GAS汇编——综合实例
- Python3 for terminal IDE 的实现
- 中国互联网的“去中心化”与“中心化”之战
- 我在南大的七年
- Apache Pig的一些基础概念及用法总结(2)
- Rotate List
- 概率统计中的样本矩和顺序统计量
- MapReduce的常用算法
- 2014华为校招机试题目总结
- C++笔试题深度分析 第五波 上
- 用MapReduce进行数据密集型文本处理 – 本地聚合(上)
- Balsamiq mockups 简介
- 排序算法——快速排序
- Apache Pig中文教程(进阶)