链表元素删除

给定一个链表,删除链表中等于给定值val的所有节点。返回删除之后的链表

例:1-->2-->3-->4-->3-->5-->3 ,  val =3,。返回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;
    }

节点类

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

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

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

猜你喜欢

转载自blog.csdn.net/wenbooboo/article/details/79963874