题解 | #从单向链表中删除指定值的节点#

从单向链表中删除指定值的节点

http://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f

Java解法

delete操作改不了头节点,即使函数内部改了,外面的头节点还是原来的,离谱……可以通过返回LNode解决这个问题 删除链表节点的方法:

  1. 分为头节点和其他节点,单独判断
  2. 定义一个新头节点,不分情况,最后返回newHead.next
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int n = in.nextInt();
        LNode head = new LNode(in.nextInt());
        for(int i=0;i<n-1;i++){
            int a = in.nextInt();
            int b = in.nextInt();
            insert(head,a,b);
        }

        int needToDelete = in.nextInt();
        head = delete(head,needToDelete);
        //为什么出来的head变不了
        //head = head.next;
        System.out.print(head.value);
        head = head.next;
        while(head!=null){
            System.out.print(" "+head.value);
            head = head.next;
        }
    }

    public static void insert(LNode head, int a, int b){
        LNode temp = head;
        while(temp!=null){
            if(temp.value==b){
                break;
            }
            temp = temp.next;
        }
        LNode x = new LNode(a,temp.next);
        temp.next = x;
    }

    public static LNode delete(LNode head, int a){
        /*LNode temp = head;
        while (temp!=null) {
            if (temp.value == a) {
                temp = temp.next;
                System.out.println(temp.toString());
            }else{
                break;
            }
        }*/
        LNode newHead = new LNode(0,head);
        LNode temp = head;
        LNode front = newHead;
        while(temp!=null){
            if(temp.value==a){
                front.next = temp.next;
                temp = temp.next;
                continue;
            }
            front = temp;
            temp = temp.next;
        }
        //System.out.println(head.toString());
        return newHead.next;
        //System.out.println(head.toString());
    }
}

class LNode{
    int value;
    LNode next;

    public LNode() {
    }

    public LNode(int value) {
        this.value = value;
    }

    public LNode(int value, LNode next) {
        this.value = value;
        this.next = next;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public LNode getNext() {
        return next;
    }

    public void setNext(LNode next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "LNode{" +
                "value=" + value +
                ", next=" + next +
                '}';
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务