剑指offer 18 删除链表的节点

链接 

 

 两个指针同时向右,cur->val = val; pre->next = cur->next;

/**
 * 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 * pre = head;
        ListNode * cur = head->next;

        while(cur != nullptr && cur->val != val) {
            pre =  pre->next;
            cur = cur->next;
        }
        pre->next = cur->next;
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/yonggandess/article/details/121390472