203 移除链表元素

2024-04-23 19:06:24 浏览数 (1)

题目:

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

示例:

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

解答

1.链表删除法

代码语言:javascript复制
public class ListNode
    {
        public int val;
        public ListNode next;
        public ListNode(int x) { val = x; }
    }
  
    public class Solution
    {
        public ListNode RemoveElements(ListNode head, int val)
        {
            while(head != null && head.val == val)
            {
                ListNode newNode = head;
                head = head.next;
                newNode.next = null;
            }
            ListNode prev = head;
            while (prev.next != null)
            {
                if (prev.next.val == val)
                {
                    ListNode newNode = prev.next;
                    prev.next = newNode.next;
                    newNode.next = null;
                }
                else
                    prev = prev.next;
            }
            return head;
        }
    }

2.递归法

代码语言:javascript复制
 public ListNode RemoveElements(ListNode head, int val) {
         if (head == null)
                return null;
            ListNode res = RemoveElements(head.next, val);
            if (head.val == val)
            {
                return res;
            }
            else
            {
                head.next = res;
                return head;
            }
    }

0 人点赞