delete list element

Given a linked list, delete all nodes in the linked list that are equal to the given value . valReturns the linked list after deletion

Example: 1-->2-->3-->4-->3-->5-->3 ,   val =3, . return 1-->2-->4-->5

    public ListNode RemoveElement(ListNode head, int val)
    {
        ListNode temp = new ListNode(0);
        temp.next = head;
        head = temp;

        while (head.next != null)
        {
            if (head.next.value == val)
            {
                head.next = head.next.next;
            }
            else
            {
                head = head.next;
            }
        }
        return temp.next;
    }

Node class

    public class ListNode
    {
        public int value;
        public ListNode next;

        public ListNode(int val)
        {
            value = val;
            next = null;
        }

        public override string ToString()
        {
            return value + "  " + next;
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325982894&siteId=291194637