1. 程式人生 > >leetcode237 Delete Node in a Linked List

leetcode237 Delete Node in a Linked List

題目連結 https://leetcode.com/problems/delete-node-in-a-linked-list/ 知識點: 考察連結串列、指標相關知識 思路: 這裡只給出了node,沒有給出val值,所以在一般情況下是不好刪除node節點的.但是可以藉助一個巧妙的方法,將node節點的下一個節點的值賦值給node節點,然後刪除node節點的下一個節點即可.同樣達到了刪除node節點的目的.注意一些邊界情況,比如node節點為空或者node節點為最後一個節點(node->next為空,直接刪除即可).

AC程式碼:

class Solution
{
public:
    void deleteNode
(ListNode* node) { if(node == NULL) return; if(node->next == NULL) { delete node; node = NULL; return; } node->val = node->next->val; ListNode* delNode = node->next; node->next =
delNode->next; delete delNode; } };

AC程式碼加測試如下:

#include <bits/stdc++.h>
using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

ListNode* createLinkedList(int arr[], int n)
{
    if(n == 0)
        return NULL;
    ListNode*
head = new ListNode(arr[0]); ListNode* curNode = head; for(int i=1; i<n; i++) { curNode->next = new ListNode(arr[i]); curNode = curNode->next; } return head; } void printLinkedList(ListNode* head) { ListNode* curNode = head; while(curNode!=NULL) { cout<<curNode->val<<" -> "; curNode = curNode->next; } cout<<"NULL"<<endl; } void deleteLinkedList(ListNode* head) { ListNode* curNode = head; while(curNode!=NULL) { ListNode* delNode = curNode; curNode = curNode->next; delete delNode; } } class Solution { public: void deleteNode(ListNode* node) { if(node == NULL) return; if(node->next == NULL) { delete node; node = NULL; return; } node->val = node->next->val; ListNode* delNode = node->next; node->next = delNode->next; delete delNode; } }; int main() { int arr[]= {1,2,3,4,5}; int n = sizeof(arr)/sizeof(int); ListNode* head = createLinkedList(arr,n); printLinkedList(head); Solution().deleteNode(head->next->next); printLinkedList(head); deleteLinkedList(head); return 0; }

在這裡插入圖片描述