LeetCode 203. Remove Linked List Elements

    xiaoxiao2021-03-25  112

    题目: 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值 。 具体思路见代码注释。

    代码:

    /** * 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) { ListNode* newhead = new ListNode(0);//在head前设置一个新的节点(定点) newhead->next = head;//指向head ListNode* pre = newhead;//设置一个pre与newhead位置一样,用于移动比较 if (head == NULL){ //如果为空链表,直接返回NULL return NULL; } while (head->next != NULL){//如果head之后还有值 if (pre->next->val == val){//pre的下一个的值与val相等,相当于是head的值与val相等,删除head pre->next = head->next; ListNode* tmp = head; head = head->next; delete tmp; } else{//不相等,直接后移 pre = head; head = head->next; } } if (head->val == val){//如果head为最后一个值,进行判断,如果相等,则删除 pre->next = NULL; delete head; } return newhead->next; } };
    转载请注明原文地址: https://ju.6miu.com/read-10286.html

    最新回复(0)