Tuesday, April 18, 2017

Delete Node in a Linked List

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 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

This question let us delete a list of nodes, more often is different, did not give us the starting point of the list, only to us to delete a node, with us before the situation is not the same, we have to delete a Node method is to have its previous node position, and then its previous node next to the next node to delete the node, and then delete the node to delete. This question is the first way to deal with the current node value with the value of the next node, and then we can delete the next node, the code is as follows:

Java Solution:

  public class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;

No comments:

Post a Comment