Remove Linked List Elements
生活随笔
收集整理的這篇文章主要介紹了
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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 正数减法
- 下一篇: 输出链表中倒数第k个结点