您的位置:首页 > Web前端 > Node.js

【LeetCode】237 & 203 - Delete Node in a Linked List & Remove Linked List Elements

2015-07-26 23:03 561 查看
237 - Delete Node in a Linked List

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is
1 -> 2 -> 3 -> 4
and you are given the third node with value
3
, the linked list should become
1 -> 2 -> 4
after calling your function.

Hide Tags: Linked List

struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x), next(NULL){}
};
void deleteNode(ListNode *node)
{
/*the main problem is that we can not know the pre ListNode of node,
so we have to copy the val one by one*/
ListNode *cur=node, *post=cur->next;
while(post)
{
cur->val=post->val;
if(post->next==NULL)
cur->next=NULL;
else
cur=post;
post=cur->next;
}
}


203 - 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

ListNode* removeElements(ListNode* head, int val)
{
ListNode *newhead=new ListNode(-1);
newhead->next=head;
ListNode *pre=newhead;
ListNode *cur=head;
while(cur)
{
if(cur->val!=val)
pre=pre->next;
else
pre->next=cur->next;
cur=cur->next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: