List - LeetCode
- Reverse Linked List
A linked list can be reversed either iteratively or recursively.
public ListNode reverseList(ListNode head) {
//reversed recursively
//head能为空吗
if (head == null || head.next == null ) {
return head;
}
//if (head.next == null || head == null) //空指针异常
//这为啥能有区别啊?
//跟下面环形链表一样,假如head直接就是null的话,那head.next就会空指针异常
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
//reversed iteratively
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode newHead = null;
while(head != null) {
ListNode temp = head.next;
head.next = newHead;
newHead = head;
head = temp;
}
return newHead;
}
LeetCode的运行数据
141. Linked List Cycle 判断链表是否有环
https://www.cnblogs.com/yorkyang/p/10876604.html
首先假如快指针的速度是慢指针的两倍,那么每移动一次,两个指针之间的距离就会加大1.
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) return false;
ListNode slow = head;
ListNode fast = head.next;
//while(fast.next != null)
//会空指针异常,因为当fast为null时,这个condition里的fast.next是空指针异常
//所以必须加上fast != null
while(fast != null && fast.next != null)
{
if (slow == fast) {
return true;
}
slow = slow.next;
fast = fast.next.next;
}
return false;
}
}
可能有的困惑
- 上面的代码中快指针的速度是慢指针的两倍,那如果是3倍,4倍呢?
在快指针的速度是慢指针的两倍的时候,它们假设有环的话,那它们之间的距离每移动一次,是减少1步的,也就是说不管这个环有多大,它们之间相距多远,每次减少1,总是能相遇的。
但是如果是3倍或更多倍的话,那有可能会错过相遇的点,因为它们之间的距离每一次移动并不是减少1的,能否刚好相遇跟相距的距离有关了。
2.判断条件的问题
这个上面代码中的注释已经说明了