203. 移除链表元素 - 力扣(LeetCode)
思路:给出一个新的指针newnode来接收,cur遍历原truct ListNode* head,tail来接收
cur->val!=val的值,最后返回newnode。
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode* newnode = NULL, * tail = NULL;
struct ListNode* cur = head;
while (cur)
{
if (cur->val != val)
{
if (tail == NULL)
{
newnode = tail = cur;
cur = cur->next;
}
else
{
tail->next = cur;
tail = tail->next;
cur = cur->next;
}
}
else
{
struct ListNode* next = cur->next;
free(cur);
cur = next;
}
if (tail)
tail->next = NULL;
}
return newnode;
}
876. 链表的中间结点 - 力扣(LeetCode)
思路:设定一个快指针fast,一个慢指针slow,fast一次走两步,slow一次走一步
这样当fast走到终点时,slow刚好走一半。
struct ListNode* middleNode(struct ListNode* head) {
struct ListNode* fast=NULL,*slow=NULL;
fast=slow=head;
while(fast && fast->next)
{
slow=slow->next;
fast=fast->next->next;
}
return slow;
}