Leetcode -- Remove Linked List Elements

来源:互联网 发布:mysql 触发器 编辑:程序博客网 时间:2024/06/07 20:05

题目:
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

分析:
删除链表中顶点值为val的node

思路:
遍历链表,遇到满足要求,就改变next指针的指向。

代码:

ListNode* removeElements(ListNode* head, int val) {        ListNode* l = new ListNode(0);        ListNode* l1 = l;        l->next = head;        while(head)        {            if(head->val == val)            {                l->next = l->next -> next;            }            else            {                l = l -> next;            }            head = head -> next;        }        return l1->next;    }
0 0
原创粉丝点击