237. Delete Node in a Linked List

来源:互联网 发布:淘宝生死狙击卖号平台 编辑:程序博客网 时间:2024/05/20 03:41

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.

s思路:
1. 链表题。看得多了,能感觉思维变活跃了,这是好事。比如,这道题,因为要删除3,但是3前面节点指针不知道,也就是说不能直接删,因为链表只能靠next来删,咋办?
2. 那就移位,把4复制到3的节点覆盖3,然后把4删除,因为4是3这个节点的next。如果让删除2,也一样的做:把3先覆盖2,然后指针移动一位,把4覆盖3,然后把4给删除!
3. 上面的做法还是啰嗦,看下图,任何情况下,先把当前值用下一个值覆盖,然后把下一个节点删除即可!分两步,无迭代!
这里写图片描述

//方法1:方法啰嗦!还是方法2好!class Solution {public:    void deleteNode(ListNode* node) {        //        while(node->next){            node->val=node->next->val;            if(!node->next->next){                node->next=NULL;                   return;            }            node=node->next;            }    }};//方法2:不需要移动所有的,这个比上面的好class Solution {public:    void deleteNode(ListNode* node) {        //        node->val=node->next->val;        node->next=node->next->next;    }};
0 0