LeetCode算法题203:移除链表元素解析

删除链表中等于给定值 val 的所有节点。
示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

这个题应该是比较简单了,但是条件还是得稍微多想想,首先如果是空链表那就一定是要返回空,此外如果表头元素是val,那就需要移动表头直到表头元素不为val。之后就好说了,如果当前节点的下一节点的值为val,那么就将当前节点指向下下一节点,否则就向前移动当前节点。C++的程序是稍显复杂的程序,python程序是优化过的程序。
C++源代码:

/**
 * 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) {
        if (head==NULL) return NULL;
        while(head!=NULL && head->val == val)
            head = head->next;
        ListNode *p = head;
        ListNode *q = NULL;
        if (p!=NULL) q = p->next;
        while(q!=NULL)
        {
            if (q->val == val)
                p->next = q->next;
            else p = p->next;
            q = q->next;
            
        }
        return head;
    }
};

python3源代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        if head==None:
            return None
        while head!=None and head.val==val:
            head = head.next
        p = head
        while p!=None and p.next!=None:
            if p.next.val == val:
                p.next = p.next.next
            else:
                p = p.next
        return head

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/83958657