欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Remove Linked List Elements

发布时间:2025/4/16 编程问答 35 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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


1、因为可能有表头是val的情况,设置辅助头结点  Head->next=head, 

2、直接在链表中考虑,头结点移动,直到不是val时再进行判断

/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:ListNode* removeElements(ListNode* head, int val) {if(head==NULL)return head;ListNode* Head=new ListNode(-1);Head->next=head;ListNode* cur=Head;while(cur->next!=NULL && cur!=NULL){if(cur->next->val==val){cur->next=cur->next->next;}else{cur=cur->next;}}return Head->next;} };
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:ListNode* removeElements(ListNode* head, int val) {if(head==NULL)return NULL;ListNode* cur=head;while(cur->val==val){cur=cur->next;if(cur==NULL)return NULL;}head=cur;ListNode* temp=head;while(temp->next!=NULL){if(temp->next->val==val){temp->next=temp->next->next;}else{temp=temp->next;}}return head;} };


总结

以上是生活随笔为你收集整理的Remove Linked List Elements的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。