继续LinkedList专题...
237. Delete Node in a Linked List
class Solution {
public void deleteNode(ListNode node) {
// ListNode prev=head;
// ListNode cur=prev.next;
// while(cur.val!=node.val){
// prev=prev.next;
// cur=cur.next;
// }
// prev.next=cur.next;
// head=prev;
node.val=node.next.val;
node.next=node.next.next;
}
}
说是删除一个节点,只给了节点值,没给原链表,有点不明所以。
用Java的最高赞解答a掉,然后给了这道题的第4603个踩...
83. Remove Duplicates from Sorted List
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode prev=head;
if(prev==null){
return null;
}
if(prev.next==null){
return head;
}
ListNode cur=prev.next;
while(cur!=null){
if(prev.val==cur.val){
prev.next=cur.next;
cur=prev.next;
}
else{
prev=prev.next;
cur=cur.next;
}
}
return head;
}
}
链表去重,经过昨天的复习已经很简单,秒过
141. Linked List Cycle
判断一个链表是否有环,挖到一个知识点!
fast-slow pointers,即快慢指针问题:
slow = slow.next;
fast = fast.next.next;
假设快慢指针原来都指向头结点,这样的话,fast指针移动速度就是slow指针的两倍。
常用场景
常被用来在O(N)时间复杂度O(1)空间复杂度的情况下,解决以下这些类型的问题:
单向链表未知长度时定位到倒数第K个节点链表判环找到链表中点
(具体解析参考https://blog.csdn.net/u014179251/article/details/89361887)
参考高赞答案:
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast)
return true;
}
return false;
}
}
今天的3题有点水,,,明天继续