首页 > 其他 > 详细

【LintCode】删除链表中的元素

时间:2016-08-01 06:53:57      阅读:139      评论:0      收藏:0      [点我收藏+]

技术分享

问题分析:

声明当前指针和上一个指针即可。

问题求解:

public class Solution {
    
    public ListNode removeElements(ListNode head, int val) {
        ListNode preListNode = new ListNode(0);// 上一个指针
        ListNode nowListNode = head;// 当前指针
        ListNode returnListNode = null;// 需要返回的链表
        preListNode.next = nowListNode;
        while (nowListNode != null) {
            if (nowListNode.val == val) {
                preListNode.next = nowListNode.next;
                nowListNode = nowListNode.next;
            } else {
                preListNode = nowListNode;
                nowListNode = nowListNode.next;
                if (returnListNode == null) {
                    returnListNode = preListNode;
                }
            }
        }
        return returnListNode;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

 

【LintCode】删除链表中的元素

原文:http://www.cnblogs.com/DarrenChan/p/5724484.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!