美文网首页
237. Delete Node in a Linked Lis

237. Delete Node in a Linked Lis

作者: 西土城小羊 | 来源:发表于2017-03-10 11:31 被阅读8次

    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.

    读题

    题目的意思很简单,就是给一个节点,然后将这个节点在链表中删除

    思路

    因为没有给出这个节点的前置节点,所以就需要换一个思路,将这个节点的值与后边节点的值进行交换,然后这个节点的next指向其后置节点的next

    题解

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public  void deleteNode(ListNode node) {
            int temp = node.next.val;
            node.next.val = node.val;
            node.val = temp;
            node.next = node.next.next;
        }
    }
    

    相关文章

      网友评论

          本文标题:237. Delete Node in a Linked Lis

          本文链接:https://www.haomeiwen.com/subject/yypngttx.html