"Leetcode" Delete Node in a Linked List

Source: Internet
Author: User

Original title Link: https://leetcode.com/problems/delete-node-in-a-linked-list/

Title Description:

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

supposed the linked list Is 3 , the linked list should become 1, 2-4  after calling your function.

Ideas:

There are two ways to delete a linked list node, one is to change the pointer, not to change the node value, and to change the node value.

Conditions only give the pointer to delete the node p, not to the head node, so can not get the pre-node p, it is not easy to let the pre point to the node after p to complete the operation of delete P.

Therefore, only through the operation of the node value to achieve the purpose of deletion. Note that this method cannot delete the last node (which can be deleted from the head node). Fortunately, the topic only requires the deletion of intermediate nodes.

Algorithm:

[Java]View PlainCopy
  1. public   void  deletenode (ListNode  node)  {  
  2.     listnode pre = node, p = node;   
  3.      while   (p.next !=  null //  when P is not the last node   
  4. P.val = P.next.val;
  5. Pre = P;
  6. p = p.next;
  7. }
  8.     pre.next = null / /  this time the pre points to the penultimate node
  9. }

"Leetcode" Delete Node in a Linked List

Related Article

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.