将链表排队-java
对于一个任务(很快就要完成),我必须将一个我手工实现的链表排队(不使用java的内置类)。有关连表如下:将链表排队-java,java,linked-list,queue,Java,Linked List,Queue,对于一个任务(很快就要完成),我必须将一个我手工实现的链表排队(不使用java的内置类)。有关连表如下: public class SnocList { private char c; private SnocList l; public SnocList(){ } public SnocList (char x, SnocList y) { this.c = x; this.l = y; } public
public class SnocList {
private char c;
private SnocList l;
public SnocList(){
}
public SnocList (char x, SnocList y) {
this.c = x;
this.l = y;
}
public char getC(){
return this.c;
}
public SnocList getL(){
return this.l;
}
public void setNext(SnocList input){
this.l = input;
}
public boolean isEmpty() {
if (this.c == 0) return true;
return false;
}
}
public class SnocQueue {
private SnocList list;
public SnocQueue(){
this.list = new SnocList();
}
public void enqueue(char c){
//I don't know what to put here
}
}
我的队列类如下所示:
public class SnocList {
private char c;
private SnocList l;
public SnocList(){
}
public SnocList (char x, SnocList y) {
this.c = x;
this.l = y;
}
public char getC(){
return this.c;
}
public SnocList getL(){
return this.l;
}
public void setNext(SnocList input){
this.l = input;
}
public boolean isEmpty() {
if (this.c == 0) return true;
return false;
}
}
public class SnocQueue {
private SnocList list;
public SnocQueue(){
this.list = new SnocList();
}
public void enqueue(char c){
//I don't know what to put here
}
}
我不知道怎么做。这看起来很简单,但我不知道怎么做。对于那些想提供帮助的人,enqueue将向列表中添加一个新节点,其中包含上一个列表的null引用(null指针)
['a'|--]-->['b'|--]-->['c'| null]在此处添加新节点要排队,您还需要一个“尾”字段和一个“头”字段,在本例中,我将创建一个类“项”的对象队列,您可以使用所需的节点
public class Item {
private int value;
private Item next;
public Item(int val) {
this.value = val;
}
public void setNext(Item item) {
this.next = item;
}
}
和队列:
public class SomeQueue {
private Item head;
private Item tail;
private int size;//size is used to verify if it has Items and avoid null references
public SomeQueue(){
this.size = 0;
}
public void enqueue(Item item) {
if (this.size > 0) {
this.tail.setNext(item);
this.tail = item;
} else { //this is when the size is 0, it means is empty
this.head = item;
this.tail = item;
}
this.size++;
}
}
正如您看到的,队列的重要部分是头和尾,setNext方法对于在节点之间进行引用也很重要
l
SnocList的引用。
l
将为null
,因为没有其他
SnocLists在链接列表中。然后,返回
以结束方法的执行else
),则使用while循环遍历链表,直到碰到一个SnocList,该SnocList对l
的引用为null
new SnocList(ch,curr.l)
指定给以前的nullcurr.l
,将新的SnocList追加到链接列表的末尾
public class SnocQueue {
SnocList head;
public void enqueue(char ch) {
if(head == null) {
head = new SnocList(ch, null);
return;
} else {
SnocList curr = head;
while (curr.l != null) {
curr = curr.l;
}
curr.l = new SnocList(ch, curr.l);
}
}
}