Remove Linked List Elements

來源:互聯網
上載者:User

標籤:鏈表刪除

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

此題的解法在與維護兩個指標。p和q,p指向當前合法的元素,q指向下一個可能合法的元素,注意是可能合法的。

p初始化為list第一個合法的元素,q的初始化為q = p->next,將q遍曆list,如果當前元素合法,則p和q都向後移動,如果當前元素不合法,則p->next=q->next,跳過這個不合法的元素。注意只有在元素合法的時候才移動p。

#include<cstdio>using namespace std;struct ListNode{int val;ListNode *next;ListNode(int x): val(x), next(NULL){}};ListNode* removeElements(ListNode *head,  int val){//p指向list中第一個合法的元素ListNode *p = head;while(p && p->val == val){p = p->next;} if(p == NULL){return NULL;} ListNode *q = p->next;head = p;//新的head指標 //用q去遍曆整個list while(q != NULL){if(q->val == val){//q指向的元素要被刪除p->next = q->next; q = q->next;//q繼續向前移動 }else {//找到了一個合法元素 p = p->next;q = q->next;}} return head;}int main(){ListNode *p = new ListNode(1);ListNode *q = new ListNode(2);p->next = q;ListNode *head = removeElements(p, 1);printf("%d", head&&head->val);return 1;} 



Remove Linked List Elements

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.