leetcode 237. Delete Node in a Linked List 删除没有父结点的元素

来源:互联网 发布:java 网站流量统计 编辑:程序博客网 时间:2024/04/29 09:05

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.

这道题很简单,就是删除一个结点,题目中说这个结点不是尾结点,所以如何删除呢?交换当前结点和下一个结点的value,然后删除下一个结点即可。

代码如下:

/*class ListNode {      int val;      ListNode next;      ListNode(int x) { val = x; }} *//* * 这个题说删除的结点不是尾结点, * 那么交换当前待删除和下一个结点的val * 然后删除下一个节点即可 *  * 这道题没哟给出父节点 * 这个第一次不太好想到 *  * */public class Solution{    public void deleteNode(ListNode node)     {        if(node==null)            return ;        else        {            int tmp=node.val;            node.val=node.next.val;            node.next.val=tmp;            node.next=node.next.next;            return ;        }    }}

下面是C++的做法,这道题明确要求删除一个节点node,但是这个节点不是尾节点,那么做法很简单了直接和下一个节点交换元素,然后删除即可

代码如下:

#include <iostream>#include <algorithm>#include <vector>#include <set>#include <string>#include <map>using namespace std;/*struct ListNode {     int val;     ListNode *next;     ListNode(int x) : val(x), next(NULL) {}};*/class Solution {public:    void deleteNode(ListNode* node)     {        if (node == NULL)            return;        else        {            int tmp = node->val;            node->val = node->next->val;            node->next->val = tmp;            node->next = node->next->next;        }    }};
阅读全文
0 0
原创粉丝点击