LeetCode-Remove Linked List Elements-解题报道

原创 2015年07月08日 18:49:44

原题链接https://leetcode.com/problems/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 


就是删除链表中所有对应值的节点。


先看是否需要删除头,然后在判断中间的。


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
		if (head == NULL)return NULL;
		ListNode *pre, *current;
		pre = head;
		current = head->next;
		while (pre != NULL && pre->val == val)
		{
			pre = current;
			if (pre != NULL)
				current = pre->next;
		}
		head = pre;
		while (current != NULL)
		{
			if (current->val == val)
				pre->next = current->next;
			
			else
				pre = current;
			current = current->next;
		}
		return head;
	}
};


相关文章推荐

LeetCode Remove Linked List Elements

题目: Remove all elements from a linked list of integers that have value val. Example Given: ...

<LeetCode OJ> 203. Remove Linked List Elements

203. Remove Linked List Elements My Submissions Question Total Accepted: 45239 Total Submissions...

关于LeetCode中Remove Linked List Elements一题的理解

题目如下: Remove all elements from a linked list of integers that have value val. Example Given: 1 --...

leetcode题解-203. Remove Linked List Elements

题目:Remove all elements from a linked list of integers that have value val.Example Given: 1 --> 2 -->...

[LeetCode]203 Remove Linked List Elements

原题链接QuestionRemove all elements from a linked list of integers that have value val.Example Given: 1...

Leetcode 203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.Example Given: 1 –> 2 –> 6 –...

Leetcode_203_Remove Linked List Elements

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/45868027 Remove all el...

leetcode 203. Remove Linked List Elements

我觉得在使用链表的时候一般有两种思路:一种是链表的内容可以修改,在原链表上进行处理,后续的操作不需要使用原链表的内容的时候这种思路可以节约空间和时间;另外一种是当我们不能更改链表的内容,后续需要用到的...

[LeetCode] Remove Linked List Elements

Remove all elements from a linked list of integers that have value val. Example Given: 1 –> 2 –> 6...

LeetCode 203 Remove Linked List Elements(移除链表元素)(Linked List)(*)

翻译从一个链表中移除所有值为val的元素。例如 给定:1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 返回:1 --> 2 --> 3 --> 4 -->...
  • NoMasp
  • NoMasp
  • 2016年01月28日 08:58
  • 1838
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode-Remove Linked List Elements-解题报道
举报原因:
原因补充:

(最多只允许输入30个字)