LeetCode 203. Remove Linked List Elements 移除链表元素 C++/Java

2023-02-14,,,,

Remove all elements from a linked list of integers that have value val.

Example:

Input:  ->->->->->->, val =
Output: ->->->->

本题的思路很简单,就是单纯的删除链表元素操作,如果头结点的元素就是给定的val值,需要借助虚结点dummy去判断。

方法一:(C++) C++中注意结点的释放

 ListNode* removeElements(ListNode* head, int val) {
ListNode* dummy=new ListNode(-),* pre=dummy;
pre->next=head;
while(pre->next){
if(pre->next->val==val){
ListNode* t=pre->next;
pre->next=pre->next->next;
t->next=NULL;
delete t;
}
else
pre=pre->next;
}
return dummy->next;
}

Java:

 public ListNode removeElements(ListNode head, int val) {
if(head==null||(head.next==null&&head.val==val))
return null;
ListNode dummy=new ListNode(-1),cur=dummy;
cur.next=head;
while(cur.next!=null){
if(cur.next.val==val)
cur.next=cur.next.next;
else
cur=cur.next;
}
return dummy.next;
}

方法二:不使用虚结点的话,最后只需要再判断一下头结点的值是否符合要求(C++)

 ListNode* removeElements(ListNode* head, int val) {
if(head==NULL)
return head;
ListNode* cur=head;
while(cur->next){
if(cur->next->val==val)
cur->next=cur->next->next;
else
cur=cur->next;
}
return (head->val==val)?head->next:head;
}

LeetCode 203. Remove Linked List Elements 移除链表元素 C++/Java的相关教程结束。

《LeetCode 203. Remove Linked List Elements 移除链表元素 C++/Java.doc》

下载本文的Word格式文档,以方便收藏与打印。