1. 程式人生 > 實用技巧 >劍指offer-18-刪除連結串列中的節點

劍指offer-18-刪除連結串列中的節點

思路:

方法一: 建立一個新連結串列指向連結串列,直接遍歷連結串列,如果找到val後將指標直接指向下個節點

程式碼:

/**
 * 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* dummy=new ListNode(-1);
        dummy->next=head;
        if(!head) return head;

        ListNode* cur=dummy;
        while(cur->next)
        {
            if(cur->next->val==val) cur->next=cur->next->next;
            else cur=cur->next;
        }
        return dummy->next;
    }
}

方法二:遞迴的思想

/** *Definitionforsingly-linkedlist. *structListNode{ *intval; *ListNode*next; *ListNode(intx):val(x),next(NULL){} *}; */ classSolution{ public: ListNode*deleteNode(ListNode*head,intval){ //遞迴的思想 if(!head)returnhead; //要刪除頭結點 if(head->val==val)returnhead->next; head->next=deleteNode(head->next,val); returnhead; } };