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

leetcode_203题——Remove Linked List Elements(链表)

时间:2015-05-07 21:43:59      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

Remove Linked List Elements

 Total Accepted: 8053 Total Submissions: 29898My Submissions

 

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

 

Hide Tags
 Linked List
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

       这道题的意思是,去掉链表中的,那些与给定的val值相同的点,即去除掉链表中的结点,这样会有可能要去掉三种(头结点,中间结点,尾结点)

所以我在第一个while循环时只考虑头结点的问题,再之后三个指针ptr1,ptr2指向当前的前后,ptr指向当前结点。

#include<iostream>

using namespace std;
//Definition for singly-linked list.
struct ListNode {
	int val;
	ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

ListNode* removeElements(ListNode* head, int val)
{
	ListNode* ptr0=head;
	ListNode* ptr=head;
	ListNode* ptr1=head;
	ListNode* ptr2=head;

	if(head==NULL)
		return head;
	while(1)
	{
		if(ptr0->val!=val)
		{
			if(ptr0->next==NULL)
				return ptr0;
			ptr1=ptr0;
			ptr=ptr0->next;
			break;
		}
		else
		{
			ptr=ptr0->next;
			free(ptr0);
			if(ptr==NULL)
				return ptr;
			else
				ptr0=ptr;		
		}
	}

	ptr1=ptr0;
	ptr=ptr0->next;

	while(1)
	{
		if(ptr->next==NULL)
		{
			if(ptr->val==val)
			{
				ptr1->next=NULL;
				free(ptr);
				return ptr0;
			}
			else
				return ptr0;
		}
		else
		{
			ptr2=ptr->next;
			if(ptr->val==val)
			{
				ptr1->next=ptr2;
				free(ptr);
				ptr=ptr2;
				ptr2=ptr->next;
			}
			else
			{
				ptr1=ptr1->next;
				ptr=ptr->next;
				ptr2=ptr2->next;
			}
		}
	}
	return ptr0;
}



int main()
{

}

  

leetcode_203题——Remove Linked List Elements(链表)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4485896.html

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