您的位置:首页 > 其它

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

2015-05-07 20:07 423 查看

Remove Linked List Elements

Total Accepted: 8053 Total Submissions: 29898My Submissions
Question Solution

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()
{

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: