代码运行总是显示顺序与插入顺序相反
public class BusLine { int id; String name; BusLine next; public BusLine(int id, String name) { this.id = id; this.name = name; } public void displayBusLine() { System.out.println(id + "->" + name); } }
public class BusLineList { private BusLine first; public BusLineList() { first = null; } public void insertFirst(int id, String name) { BusLine newBusLine = new BusLine(id, name); newBusLine.next = first; first = newBusLine; } public void displayList() { BusLine current = first; while (current != null) { current.displayBusLine(); current = current.next; } } public BusLine delete(String name) { BusLine current = first; BusLine previous = first; if (current != null && name != null) { while (current.next != null && !name.equals(current.name)) { previous = current; current = current.next; } } if (current == first) first = first.next; else if (previous != null) { previous.next = current.next; } return current; } public BusLine find(String name) { BusLine current = first; if (current != null && name != null) { while (current.next != null && !name.equals(current.name)) { current = current.next; } } return current; } }
public class BusLineApp { public static void main(String[] args) { BusLineList busLineList = new BusLineList(); int i = 0; busLineList.insertFirst(++i, "市光路"); busLineList.insertFirst(++i, "嫩江路"); busLineList.insertFirst(++i, "翔殷路"); busLineList.insertFirst(++i, "黄兴公园"); busLineList.delete("翔殷路"); busLineList.displayList(); BusLine currentBusLine = busLineList.find("黄兴公园"); System.out.println(currentBusLine.id); System.out.println(currentBusLine.name); } }
相关分类