java 添加方法_Java链接列表 – 添加方法

数据结构类,实现具有头,尾和当前节点的单链表.如果遇到方法问题,可以在正确的方向上使用微调.

从赋值,编写方法:

add(item):在列表中的当前节点之后添加item(String),并设置当前指针以引用新节点.

我的尝试:

public void add(String item)

{

if(curr != null)

{

Node newNode = new Node(item, curr.next);

curr.next = newNode;

curr = newNode;

}

else

{

head = tail = new Node(item, null);

curr = head;

}

}

我的添加方法似乎只在我将项目添加到列表中间时才起作用,而不是在任何一端.如果我使用它来添加一些项目然后打印列表,只有我添加的第一个项目将在列表中,而我的prepend和append方法测试得很好.

我的代码有什么明显的问题吗?我觉得我错过了一些明显的东西.

所有:

public class LinkedList {

Node head = null; /* Head of the list */

Node tail = null; /* Tail of the list */

Node curr = null; /* Current node in the list */

public void prepend(String item) {

if (head == null) {

head = tail = new Node(item, null);

curr = head;

} else {

head = new Node(item, head);

curr = head;

}

}

public void append(String item) {

if (head == null) {

head = tail = new Node(item, null);

curr = tail;

} else {

tail.next = new Node(item, null);

tail = tail.next;

curr = tail;

}

}

public void add(String item) {

if (curr != null) {

Node newNode = new Node(item, curr.next);

curr.next = newNode;

curr = newNode;

} else {

head = tail = new Node(item, null);

curr = head;

}

}

public void delete() {

if (curr.next == null) {

Node temp = head;

while (temp.next != curr) {

System.out.println(temp.item);

temp = temp.next;

}

temp.next = null;

curr = head;

}

}

public void find(String item) {

Node temp = new Node(curr.item, curr.next);

if (item.equals(temp.item))

curr = temp;

else {

temp = temp.next;

while (temp.next != null && temp != curr) {

if (item.equals(temp.item))

curr = temp;

}

}

}

public String get() {

if (curr != null)

return curr.item;

else

return "";

}

public boolean next() {

if (curr != tail) {

curr = curr.next;

return true;

} else

return false;

}

public void start() {

curr = head;

}

public void end() {

curr = tail;

}

public boolean empty() {

if (head == null)

return true;

else

return false;

}

}

节点类:

class Node {

Node next;

String item;

Node(String item, Node next) {

this.next = next;

this.item = item;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值