博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 203 Remove Linked List Elements
阅读量:7091 次
发布时间:2019-06-28

本文共 2067 字,大约阅读时间需要 6 分钟。



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

Example

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

我的解法:

// Linklist.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include
using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* removeElements(ListNode* head, int val) { if(head == NULL)return head; ListNode* pre = NULL; ListNode* root = head; ListNode* current = head; while(current!=NULL) { if(current->val == val) { if(pre==NULL) { current = current->next; root = current; } else { pre->next = current->next; current = current->next; } } else { pre = current; current =current->next; } } return root; }int _tmain(int argc, _TCHAR* argv[]){ ListNode* temp = new ListNode(2); ListNode* temp_next = new ListNode(1); temp->next = temp_next; removeElements(temp,1); return 0;}

python的解法:

class Solution:    # @param {ListNode} head    # @param {integer} val    # @return {ListNode}    def removeElements(self, head, val):        dummy = ListNode(-1)        dummy.next = head        prev = dummy        while head:            if head.val == val:                prev.next = head.next                head = prev            prev = head            head = head.next        return dummy.next

一个非常简洁的解法:

struct ListNode* removeElements(struct ListNode* head, int val) {    if (head&&head->val==val)head=removeElements(head->next, val);    if (head&&head->next)head->next=removeElements(head->next, val);    return head;}

你可能感兴趣的文章
js实现栈
查看>>
前端必备,50 个 Chrome Developer Tools 必备技巧
查看>>
客户故事:4家银行如何打造新一代移动金融中心
查看>>
NDK开发中这些基本知识你都懂吗
查看>>
自动化运维工具ansible的实践
查看>>
一个22万张NSFW图片的鉴黄数据集?我有个大胆的想法……
查看>>
do 一下来了一个 redux
查看>>
Vue教程09:双向绑定对象中属性原理
查看>>
如何实现VM框架中的数据绑定
查看>>
关于this
查看>>
[译] 系列教程:选择准备安装的 TensorFlow 类型
查看>>
Webhook到底是个啥?
查看>>
Flutter学习 ---- TravisCI加持
查看>>
借用UAC完成的提权思路分享
查看>>
『中级篇』 Linux网络命名空间(25)
查看>>
JS计算精度小记
查看>>
js的各种距离计算(较全)
查看>>
微信小程序异步API为Promise简化异步编程
查看>>
关于java泛型大大小小的那些事
查看>>
此面试题版本落后-请勿观看
查看>>