您的位置:首页 > 其它

[leetcode-203]Remove Linked List Elements(c)

2015-08-26 19:42 267 查看
问题描述:

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

Credits:

Special thanks to @mithmatt for adding this problem and creating all test cases.

分析:注意链表的头部即可。

代码如下:8ms

[code]/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    if(!head)
        return head;
    struct ListNode* tmpNode=head;
    struct ListNode* prevNode = NULL;

    while(tmpNode){
        if(tmpNode->val==val){
            if(!prevNode){
                head = tmpNode->next;
            }else{
                prevNode->next = tmpNode->next;
            } 
        }else{
            prevNode = tmpNode;
        }
        tmpNode = tmpNode->next;
    }
    return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: