I will also click LeetCode -- 2. Delete Node in a Linked List, leetcodelinked

Source: Internet
Author: User

I will also click LeetCode -- 2. Delete Node in a Linked List, leetcodelinked

This question means that you need to write a function to delete a node, but the last node is not in a single-chain table ...), only the node to be deleted. If the linked list is 1-> 2-> 3-> 4, you are given a third node with a value of 3, this linked list should be like this 1-> 2-> 4 after you call your function ......

It cannot delete the end node, so we need to determine the end node. To determine whether a node is the end node, you only need to determine whether node-> next is null. When we write the delete operation of the linked list, we will access the previous node of the node to be deleted, and then direct the next of the previous node to the next node of the node to be deleted, then release the node.

Here, we cannot access the previous node of the node to be deleted, so we cannot delete the node by simply changing the pointer. However, we can achieve the final effect by copying nodes. We will copy the value of the next node of the node to be deleted. At this time, the two nodes are exactly the same, and we release another node, which is equivalent to deleting a node. So the answer to this question is like this, although changing the pointer pointing is the easiest way ......

 1 /** 2  * Definition for singly-linked list. 3  * struct ListNode { 4  *     int val; 5  *     ListNode *next; 6  *     ListNode(int x) : val(x), next(NULL) {} 7  * }; 8  */ 9 class Solution {10 public:11     void deleteNode(ListNode* node) {12         if (node == nullptr) {13             return;14         }15         if (node->next != nullptr){16             ListNode* t = node->next;17             node->val = node->next->val;18             node->next = node->next->next;19             delete t;20         }21     }22 };

 

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.