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(-);
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;
}
}
04-13 13:25