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

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



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;}

转载于:https://www.cnblogs.com/wangyaning/p/7853999.html

你可能感兴趣的文章
mysql中sql语句
查看>>
head/tail实现
查看>>
sql语句的各种模糊查询语句
查看>>
vlc 学习网
查看>>
Python20-Day05
查看>>
Real World Haskell 第七章 I/O
查看>>
C#操作OFFICE一(EXCEL)
查看>>
【js操作url参数】获取指定url参数值、取指定url参数并转为json对象
查看>>
ABAP 程序间的调用
查看>>
git分支管理
查看>>
移动端单屏解决方案
查看>>
一位资深Java架构师的晋级心得
查看>>
ass1_1
查看>>
senfile函数实例的运行过程截图
查看>>
程序编辑SHP文件并应用更改到数据源
查看>>
VS中C#读取app.config数据库配置字符串的三种方法(转)
查看>>
读取 android的内存、cpu、流量等 信息
查看>>
Python入门系列教程(三)列表和元组
查看>>
关于linux安装前规划分区二三事
查看>>
Educational Codeforces Round 39 B Weird Subtraction Process
查看>>