当先锋百科网

首页 1 2 3 4 5 6 7

剑指 Offer 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) {
        ListNode* newHead = new ListNode(0);
        newHead->next = head;
        for(ListNode* p = newHead; p->next; p = p->next) {
            if(p->next->val == val) {
                p->next = p->next->next;
                break;
            }
        }
        return newHead->next;
    }
};