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

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

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

解题思路

定义两个指针pre和cur,如果cur的值为val,则删除该结点。需要注意的情况有两种:①需要删除头结点;②链表为空。

实现代码[C++]

//Runtime:38ms#include 
using namespace std;struct ListNode{ int val; ListNode *next; ListNode(int x) : val(x), next(NULL){}};class Solution {public: ListNode* removeElements(ListNode* head, int val) { while (head != NULL && head->val == val) { head = head->next; } if (head == NULL) { return NULL; } ListNode *pre = head; ListNode *cur = head->next; while(cur != NULL) { if (cur->val == val) { pre->next = pre->next->next; } else { pre = pre->next; } cur = cur->next; } return head; }};void print(ListNode *head){ while (head != NULL) { cout<
val; head = head->next; } cout<
next = node2; node2->next = node3; node3->next = node4; print(node1); node1 = s.removeElements(node1, 2); print(node1);}

实现代码[Python]

# Rumtime:181msclass ListNode:    def __init__(self, x):        self.val = x        self.next = Noneclass Solution:    # @param {ListNode} head    # @param {integer} val    # @return {ListNode}    def removeElements(self, head, val):        while head != None and head.val == val:            head = head.next        if head == None:            return None        pre = head        cur = head.next        while cur != None:            if cur.val == val:                pre.next = pre.next.next            else:                pre = pre.next            cur = cur.next        return headdef printList(head):    # @param {ListNode} head    while head != None:        print(head.val, end = ' ')        head = head.next    print() # print '\n'node1 = ListNode(1)node2 = ListNode(2)node3 = ListNode(1)node4 = ListNode(2)node1.next = node2node2.next = node3node3.next = node4printList(node1) # print the origin lists = Solution();node1 = s.removeElements(node1, 1)printList(node1) # print the result list

转载地址:http://xmkum.baihongyu.com/

你可能感兴趣的文章
SQL语句重复数据取一条
查看>>
多次调用 android onmesure onlayout
查看>>
Matlab教程2_ 绘图 _ 二维
查看>>
五种情况下Win7或重蹈Vista覆辙
查看>>
Timer定时器
查看>>
Win7、Ubuntu双系统正确卸载Ubuntu系统
查看>>
两数互换的例子
查看>>
我的友情链接
查看>>
网络拓扑自动发现-Sugarnms智能网管软件的基础
查看>>
线程的状态转换图
查看>>
我的友情链接
查看>>
在interface builder中设置多个等比例排列的View
查看>>
VMware vSphere 5.0 五大改变
查看>>
spring注解性的事物@Transactional不起作用
查看>>
我的友情链接
查看>>
zookeeper常用使用场景
查看>>
高性能HTTP加速器Varnish(概念篇)
查看>>
使用aulayout自适应uitableviewcell高度
查看>>
selinux学习笔记
查看>>
pureftpd服务器的配置
查看>>