码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Remove Linked List Elements

时间:2015-09-10 07:13:45      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5


解题思路:

方法一:

使用“哑节点”记录链表头部。

需要使用一个变量cur记录当前节点。

The key to solve this problem is using a helper node to track the head of the list.

方法二:

使用递归recursion


Java code:

Method1

//The key to solve this problem is using a helper node to track the head of the list.
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode cur = dummy;
        while(cur!=null && cur.next!= null) {
            if(cur.next.val == val) {
                cur.next = cur.next.next;
            }else {
                cur = cur.next; 
            }
        }
        return dummy.next;
 
    }

Method2

public ListNode removeElements(ListNode head, int val) {
        if (head == null) return null;
        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head;
    }

Reference:

1. http://bookshadow.com/weblog/2015/04/24/leetcode-remove-linked-list-elements/

2. http://www.programcreek.com/2014/04/leetcode-remove-linked-list-elements-java/

 

Leetcode Remove Linked List Elements

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/4796659.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!