码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Remove Linked List Elements

时间:2015-05-11 18:06:30      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

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


思路分析:在链表头节点前插入一个新节点,方便删除操作。


代码:

class Solution
{
	public:
		ListNode * removeElements(ListNode * head,int val)
		{
			ListNode * new_node = new ListNode(-1);
			new_node->next = head;
			ListNode * first = new_node;
			ListNode * second = new_node->next;
			while(second != NULL)
			{
				if(second->val == val)
				{
					first->next = second->next;
					second = first->next;
				}
				else
				{
					first = second;
					second = second->next;
				}
			}
			ListNode * temp = new_node->next;
			delete new_node;
			return temp;
		}
}


LeetCode:Remove Linked List Elements

标签:

原文地址:http://blog.csdn.net/yao_wust/article/details/45645219

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!