单链表常见操作

来源:互联网 发布:麻省理工学院算法导论 编辑:程序博客网 时间:2024/05/16 08:26
public class SinglyLinkList<Item> {private Node head;private int N;private class Node{Item item;Node next;public Node() {}public Node(Item item,Node next){this.item = item;this.next = next;}}public SinglyLinkList() {this.head = new Node();}public SinglyLinkList(Item[] a){this();Node p = this.head;for(int i=0; i<a.length; i++){p.next = new Node(a[i],null);//尾插p = p.next;N++;}}public boolean isEmpty(){return N==0;}public int size(){return N;}/** * 返回第i个元素 */public Item get(int i){if(i>0 && i<=N){Node p = this.head.next;for(int j=1; j<i; j++)p = p.next;return p.item;}return null;}/** * 在第i个结点前插入x */public void insert(int i,Item x){if(x==null)return;if(i>=1 && i<=N){Node p = this.head;for(int j=1; j<i; j++)p = p.next;p.next = new Node(x,p.next);N++;}}/** * 删除第i个结点 */public Item remove(int i){if(i<1 || i>N)return null;else{Node p = this.head;for(int j=1; j<i; j++)p = p.next;Item item = p.next.item;p.next = p.next.next;N--;return item;}}/** * 删除单链表所有元素 */public void removeAll(){this.head.next = null;N = 0;}/** * 将链表逆序 */public void reverse(){Node p = this.head.next,second=null,reverse=null;while(p!=null){second = p.next;p.next = reverse;reverse = p;p = second;}this.head.next = reverse;}/** * 遍历单链表中所有元素 */public void display(){Node p = this.head.next;System.out.println("链表中所有元素为:");if(N==0){System.out.println("此链为空!");return;}while(p!=null){System.out.print(p.item+" ");p = p.next;}System.out.println();}public static void main(String[] args) {String[] s = {"A","B","C","D","E"};SinglyLinkList<String> sll = new SinglyLinkList<String>(s);sll.display();System.out.println("链中第1个元素为:"+sll.get(1));System.out.println("链中第5个元素为:"+sll.get(5));//sll.insert(1, "X");//sll.display();//sll.remove(1);//sll.remove(3);//sll.display();//sll.reverse();//sll.display();sll.removeAll();sll.display();}}