zoukankan      html  css  js  c++  java
  • 【LeetCode】237 & 203

    237 - 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.

    Hide Tags: Linked List

    struct ListNode{
        int val;
        ListNode *next;
        ListNode(int x):val(x), next(NULL){}
    };
    void deleteNode(ListNode *node)
    {
        /*the main problem is that we can not know the pre ListNode of node,
          so we have to copy the val one by one*/
        ListNode *cur=node, *post=cur->next;
        while(post)
        {
            cur->val=post->val;
            if(post->next==NULL)
                cur->next=NULL;
            else
                cur=post;
            post=cur->next;
        }
    }

    203 - Remove Linked List Elements

    Remove all elements from a linked list of integers that have value val.

    Example
    Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
    Return: 1 --> 2 --> 3 --> 4 --> 5

    ListNode* removeElements(ListNode* head, int val)
    {
        ListNode *newhead=new ListNode(-1);
        newhead->next=head;
        ListNode *pre=newhead;
        ListNode *cur=head;
        while(cur)
        {
            if(cur->val!=val)
                pre=pre->next;
            else
                pre->next=cur->next;
            cur=cur->next;
        }
    }
  • 相关阅读:
    软件工程概论-用户登录界面
    2016.11.25异常处理
    2016.11.18多态
    2016.11.11继承与接口
    11.6数组
    10.28字符串加密等
    python 读写文件
    python可变的类型、不可变的类型
    python 字典练习 记录学生是否交作业的小程序
    python字典
  • 原文地址:https://www.cnblogs.com/irun/p/4678947.html
Copyright © 2011-2022 走看看