[LeetCode练习题-C语言]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
我的答案
错误在于:
删除链表元素,不能直接赋值,而应该将此节点前一个节点的指针指到后一个节点上。
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode *temp = head;
struct ListNode *node ;
while(head != NULL && head->next != NULL)
{
if(head->val == val){
head->val = head->next->val;
head->next = head->next->next;
}
head = head->next;
}
if(head->val == val){
//错误!
head = NULL;
}
return temp;
}
思路:链表开头与数字相同的,可以直接通过指向next删除,链表中与next相同的,将此节点前一个节点的指针指到后一个节点上。
别人的答案1:
ListNode* removeElements(ListNode* head, int val) {
ListNode* currNode = head;
while (true) {
if (head == NULL) return NULL;
if (currNode->val != val) break;
currNode = currNode->next;
head = currNode;
}
while (currNode->next) {
if (currNode->next->val == val) {
currNode->next = currNode->next->next;
} else {
currNode = currNode->next;
}
}
return head;
}
别人的答案2
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode* pre, *p;
pre = p = head;
while ( p )
{
if ( p->val == val)
{
if ( p == head)
{
pre = head = p->next;
}
else
{
pre->next = p->next;
}
free(p);
p = p->next;
}
else
{
pre = p;
p = p->next;
}
}
return head;
}