18. 删除链表节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
if(head == nullptr)
return nullptr;
if(head->val == val)
return head->next;
ListNode* cur = head;
ListNode* prev = nullptr;
while(cur)
{
if(cur->val == val){
prev->next = cur->next;
}
prev = cur;
cur = cur->next;
}
return head;
}
};
22. 链表中倒数第K个节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
// K <= 0的情况
if(head == nullptr || k <= 0){
return nullptr;
}
ListNode* back = head;
ListNode* list = head;
while(k--){
//k大于链表长度
if(back == nullptr && k != 0){
return nullptr;
}
back = back->next;
}
while(back)
{
list = list->next;
back = back->next;
}
return list;
}
};