java链表ListNode

/**
* 描述:

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

样例:

给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。

分析:

1.首先判断head是不是空,为空就直接返回null
2.然后从head.next开始循环遍历,删除相等于val的元素
3.最后判断head是否和val相等,若相等,head = head.next
(这里最后判断head是有原因的,因为head只是一个节点,只要判断一次,如果最先判断head就比较麻烦,因为如果等于val,head就要发生变化)
这里也体现出为什么设计链表的时候要空出一个头结点

*/

package leetcode;

class ListNode{
int val;
ListNode nextNode;
ListNode(int val){
this.val=val;
this.nextNode=null;
}
}
public class n2deletelistnode {

static ListNode  head=null;
public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] input=new int[]{1,2,3,3,4,4,5};
    ListNode listNode=buildListNode(input);
    head=listNode;
    while(listNode!=null){
        System.out.println("val"+listNode.val+"/listNode"+listNode.nextNode);
        listNode=listNode.nextNode;
    }
    head=removeElements(head,3);
    listNode=head;
    while(listNode!=null){
        System.out.println("val"+listNode.val+"/listNode"+listNode.nextNode);
        listNode=listNode.nextNode;
    }

}
private static ListNode buildListNode(int[] input){
    ListNode first = null,last = null,newNode;
    int num;
    if(input.length>0){
        for(int i=0;i<input.length;i++){
            newNode=new ListNode(input[i]);
            newNode.nextNode=null;
            if(first==null){
                first=newNode;
                last=newNode;
            }
            else{
                last.nextNode=newNode;
                last=newNode;
            }

        }
    }
    return first;
}
private static ListNode removeElements(ListNode head,int val){
    if(head==null){
        return null;
    }
    ListNode p=head,q=head.nextNode;
    while(q!=null){
        if(q.val==val){
            p.nextNode=q.nextNode;
            q=q.nextNode;
        }else{
            p=p.nextNode;
            q=q.nextNode;
        }
    }
    if(head.val==val){
        return head.nextNode;
    }
    return head;

}

}

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值