java linkedlist 删除,java - 如何从linkedlist中删除节点?

This code is a table that has an option to Inert name, delete, show, and quit .

this code run's well but my only problem is on how to delete a chosen name in a node

class Node{

Node in;

String name;

public Node(){

in = null;

}

public Node(String n){

in = null;

name = n;

}

public void setIn(Node n){

in = n;

}

public Node getIn(){

return in;

}

public void setName(String n){

name = n;

}

public String getName(){

return name;

}

public class Main{

public static void main(String args[]){

Scanner scan = new Scanner(System.in);

LinkedList bi = new LinkedList();

while(true){

System.out.println("Choose!\n[a] Insert Name\n[b] Delete\n[c] Show\n[d] Exit");

char c = scan.next().charAt(0);

System.out.println();

if(c == 'a'){

System.out.print("Enter Name: ");

bi.insert(scan.next());

System.out.println();

}

else if(c == 'b'){

System.out.print("Enter Name to delete: ");

bi.delete(scan.next());

System.out.println();

}

else if(c == 'c'){

bi.show();

System.out.println();

}

else if(c == 'd'){

System.exit(0);

}

}

}

}

class LinkedList{

private Node root;

public LinkedList(){

root = null;

}

public void insert(String n){

root = insert(root, n);

}

private Node insert(Node n, String r){

if(n == null){

n = new Node(r);

}

else{

n.in = insert(n.in, r);

}

return n;

}

public void delete(String n){

root = delete(root, n);

}

private Node delete(Node n, String r){

}

public void show(){

show(root);

}

private Node show(Node n){

if(n == null){

System.out.println("Empy list!");

}

else{

while(n!=null){

System.out.println(n.getName());

n = n.getIn();

}

}

return n;

}

}

*i don't know how to delete a node . What should i put on my delete method?

public void delete(String n){

root = delete(root, n);

}

private Node delete(Node n, String r){

}

解决方案

To delete Node you actually need to update it's previous node's in to be deleting Node's in, and the left alone Node will eventually get garbage collected.

Just one catch if node to be deleted is the root node than update root node.

private Node delete(Node root, String data)

{

Node n=null;

//in case list is empty then return

if(root==null) return n;

if (root.name.equals(data))

{

n = root;

root = null;

return n;

}

while(root.in!=null)

{

if (root.in.name.equals(data))

{

//save the reference

n=root.in;

//making root.in to be garbage collected

root.in = root.in.in;

break;

}

root = root.in;

}

return n;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值