删除链表的节点
删除节点 用虚拟头节点
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
if(head==NULL) return NULL;
ListNode* dummyHead=new ListNode();
dummyHead->next=head;
ListNode* cur=dummyHead;
while(cur->next!=NULL)
{
if(cur->next->val==val)
{
cur->next=cur->next->next;
break;
}
cur=cur->next;
}
return dummyHead->next;
}
};
2.链表中倒数第K个节点
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode* slow=head;
ListNode* fast=head;
while(k--)
{
fast=fast->next;
}
while(fast!=NULL)
{
slow=slow->next;
fast=fast->next;
}
return slow;
}
};