我有一项任务,我在涉及双重链接列表时非常失败(注意,我们应该从头开始创建它,而不是使用内置API)。该计划应该基本上跟踪信用卡。我的教授希望我们使用双向链表来实现这一目标。问题是,这本书没有详细介绍这个主题(甚至没有显示涉及双链表的伪代码),它只描述了双重链接列表是什么,然后与图片进行对话,而在一个小段落中没有代码。但无论如何,我已经抱怨了。我完全理解如何创建节点类及其工作原理。问题是如何使用节点创建列表?这是我到目前为止所拥有的。
public class CardInfo
{
private String name;
private String cardVendor;
private String dateOpened;
private double lastBalance;
private int accountStatus;
private final int MAX_NAME_LENGTH = 25;
private final int MAX_VENDOR_LENGTH = 15;
CardInfo()
{
}
CardInfo(String n, String v, String d, double b, int s)
{
setName(n);
setCardVendor(v);
setDateOpened(d);
setLastBalance(b);
setAccountStatus(s);
}
public String getName()
{
return name;
}
public String getCardVendor()
{
return cardVendor;
}
public String getDateOpened()
{
return dateOpened;
}
public double getLastBalance()
{
return lastBalance;
}
public int getAccountStatus()
{
return accountStatus;
}
public void setName(String n)
{
if (n.length() > MAX_NAME_LENGTH)
throw new IllegalArgumentException("Too Many Characters");
else
name = n;
}
public void setCardVendor(String v)
{
if (v.length() > MAX_VENDOR_LENGTH)
throw new IllegalArgumentException("Too Many Characters");
else
cardVendor = v;
}
public void setDateOpened(String d)
{
dateOpened = d;
}
public void setLastBalance(double b)
{
lastBalance = b;
}
public void setAccountStatus(int s)
{
accountStatus = s;
}
public String toString()
{
return String.format("%-25s %-15s $%-s %-s %-s",
name, cardVendor, lastBalance, dateOpened, accountStatus);
}
}
public class CardInfoNode
{
CardInfo thisCard;
CardInfoNode next;
CardInfoNode prev;
CardInfoNode()
{
}
public void setCardInfo(CardInfo info)
{
thisCard.setName(info.getName());
thisCard.setCardVendor(info.getCardVendor());
thisCard.setLastBalance(info.getLastBalance());
thisCard.setDateOpened(info.getDateOpened());
thisCard.setAccountStatus(info.getAccountStatus());
}
public CardInfo getInfo()
{
return thisCard;
}
public void setNext(CardInfoNode node)
{
next = node;
}
public void setPrev(CardInfoNode node)
{
prev = node;
}
public CardInfoNode getNext()
{
return next;
}
public CardInfoNode getPrev()
{
return prev;
}
}
public class CardList
{
CardInfoNode head;
CardInfoNode current;
CardInfoNode tail;
CardList()
{
head = current = tail = null;
}
public void insertCardInfo(CardInfo info)
{
if(head == null)
{
head = new CardInfoNode();
head.setCardInfo(info);
head.setNext(tail);
tail.setPrev(node) // here lies the problem. tail must be set to something
// to make it doubly-linked. but tail is null since it's
// and end point of the list.
}
}
}
这是作业本身,如果它有助于澄清所需要的内容,更重要的是,我不理解的部分。谢谢 https://docs.google.com/open?id=0B3vVwsO0eQRaQlRSZG95eXlPcVE
答案 0 :(得分:0)
我认为CardList
旨在封装实际的双向链表实现。
考虑只有一个节点的DLL的基本情况:节点的prev
和next
引用将为null(或自身)。列表的封装head
和tail
引用都是单个节点(因为节点既是列表的开头也是结尾)。有什么难以理解的?
注意:假设CardList
是DLL结构的封装(而不是操作),它没有理由拥有CardInfoNode current
字段,因为这种状态信息只对在结构上工作的算法,这将维护自己(它也使你的类线程不安全)。