Remove list elements - list

topic

Delete the list is equal to a given value  val  all nodes.

Example:

Input: . 1 -> 2 -> . 6 -> . 3 -> . 4 -> 5 -> . 6 , Val = . 6 
Output: . 1 -> 2 -> . 3 -> . 4 -> 5

 

Thinking

1 first determines whether the list is empty, and the first node of the list is not equal to val (the deleted node), the cycle is not equal to the first traversing node of val

2. p.next determines whether the node is empty, and then determines p.next.val == val 

    If they are equal, then point to the next node p.next p.next = p.next?.next

    If not equal, the elements will shift continues to determine p = p.next!

3. Return head, to complete the operation

 

Code

public class ListNode {
    public var val: Int
    public var next: ListNode?
    public init (_ val: Int) {
        self.val = val
        self.next = nil
    }
}

func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
    head var = head // SWIFT is let pass the immutable, the variable var into 
    the while head! = nil && head? .val == Val {
        head = head?.next
    }
    if head == nil {
        return head
    }
    var p: ListNode = head!
    while p.next != nil {
        if p.next?.val == val {
            p.next = p.next?.next
        } else {
            p = p.next!
        }
    }
    return head
}

 

result

 

 

Guess you like

Origin www.cnblogs.com/guohai-stronger/p/11959337.html