算法思想:
没看答案:
- 先声明哨兵节点pre防止head头节点的值等于val的情况;
- 声明快慢指针slow和fast,当fast不等于val时,slow = fast, fast前进到fast->next;
- 当fast等于val时,slow->next等于fast->next,slow不前进,fast前进到fast->next。
- 最后返回pre->next即可。
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head == nullptr) return head;
ListNode* pre = new ListNode(100);
pre->next = head;
ListNode* slow = pre;
ListNode* fast = pre->next;;
while(fast != nullptr){
if(fast->val == val){
slow->next = fast->next;
fast = fast->next;
}else{
slow = fast;
fast = fast->next;
}
}
return pre->next;
}
};
python
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
curr1 = pHead
curr2 = pHead
while curr2 != None and curr2.next != None:
curr1 = curr1.next
curr2 = curr2.next.next
if curr1 == curr2:
ptr = pHead
while ptr != curr1:
ptr = ptr.next
curr1 = curr1.next
return ptr
return None
复杂度分析:
- 时间复杂度:O(n)。
- 空间复杂度:O(1)。