java 单链表
public class Node_Single { private String key;//节点的值 private Node_Single next;//指向下一个的指针 public Node_Single(String key){//初始化head this.key = key; this.next = null; } public Node_Single(String key,Node_Single next){ this.key = key; this.next = next; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Node_Single getNext() { return next; } public void setNext(Node_Single next) { this.next = next; } @Override public String toString() { return "Node_Single [key=" + key /*+ ", next=" + next +*/ +"]"; } }
public class SingleList { private Node_Single head = null;//头节点 //初始化 public void initList() { head = new Node_Single(null); head.setNext(null); } //得到最后一个元素 public Node_Single getTailNode() { Node_Single p = head.getNext(); Node_Single q = head; while(p != null) { q = p; p = p.getNext(); } return q; } //添加 public void addtoList(Node_Single node) { if(head == null) { initList(); } Node_Single p = head.getNext(); Node_Single q = head; while(p != null) { q = p; p = p.getNext(); } q.setNext(node); node.setNext(null); } //删除 public void deletetoList(Node_Single node) { Node_Single p = head.getNext(); Node_Single q = head; while((p.getKey() != node.getKey())&&(p != null)) { q = p; p = p.getNext(); } if(p != null) { q.setNext(p.getNext()); } } //打印链表 public void printList() { Node_Single p = head.getNext(); while(p != null) { System.out.println(p); p = p.getNext(); } } //反转链表 public void reverseList() { Node_Single p = new Node_Single(null); Node_Single q = new Node_Single(null); p = head.getNext(); while(p.getNext() != null) { q = p.getNext(); p.setNext(q.getNext()); q.setNext(head.getNext()); head.setNext(q); } } public static void main(String[] args) { SingleList singleList = new SingleList(); Node_Single node1 = new Node_Single("1"); Node_Single node2 = new Node_Single("2"); Node_Single node3 = new Node_Single("3"); Node_Single node4 = new Node_Single("4"); Node_Single node5 = new Node_Single("5"); Node_Single node6 = new Node_Single("6"); singleList.addtoList(node1); singleList.addtoList(node2); singleList.addtoList(node3); singleList.addtoList(node4); singleList.addtoList(node5); singleList.addtoList(node6); singleList.deletetoList(node3); singleList.reverseList(); singleList.printList(); } }