LeetCode 203 Remove Linked List Elements(链表操作)

来源:互联网 发布:java解决高并发问题 编辑:程序博客网 时间:2024/05/30 23:41

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

解题思路:基本的链表删除操作,没啥思路。就是要注意删除第一个元素的情况。

代码如下:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */ struct ListNode* removeElements(struct ListNode* head, int val) {    while(head && head->val == val) head = head->next;    struct ListNode* last = head;    struct ListNode* now = head;    while(now){        if(now->val == val){            last->next = now->next;            free(now);            now = last->next;        }else{            last = now;            now = now->next;        }    }    return head;}

0 0
原创粉丝点击