61-旋转链表

61-旋转链表

力扣61

https://leetcode-cn.com/problems/rotate-list/

比较简单,别那么傻每次都交换,先往后找到该去的位置,截成两段,直接对调

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null) return head;
ListNode pre = head, post = head;
while (k-- != 0){
pre = pre.next != null ? pre.next : head;
}
while (pre.next != null){ //前后一起移动找到分割点post
pre = pre.next;
post = post.next;
}
pre.next = head;
head = post.next;
post.next = null;
return head;
}

1707 ms 37.8 MB Java


优化一下,别那么傻,k可能很大,头尾循环1000多次…,直接循环一次,得出链表的大小,然后k % count即可得到该去的位置了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null) return head;
ListNode pre = head, post = head;
int count = 1;
while (pre.next != null){ //遍历1次获得链表长度
pre = pre.next;
count++;
}
k = k % count; //计算位置
pre = head;
while (k-- != 0) pre = pre.next; //就不用头尾循环了
while (pre.next != null){
pre = pre.next;
post = post.next;
}
pre.next = head;
head = post.next;
post.next = null;
return head;
}


其他链表类型的题目点击这里

#
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×