一个单向链表的实现
因为存在链表的面试题 所以在这里实现一下
在书中 关于链表的面试题都是单向链表 可能是因为这样题目会更有挑战 所以这里就实现一个单向链表
其中有一些方法是为了以后做题方便加进去的 一般的单向链表可能 Node 类都是不可见的 这里全都是 public 的 并且提供返回 head tail 等等关于 node 的方法 是为了做题方便
实际面试的时候当然是选用最合适的实现 并且将 head tail 之类的成员变量变成 public 更加方便答题 这里只是为了再练习一下java泛型 所以实现起来比较麻烦
后面有关链表的题 都是使用这个链表或者是 extends 这个链表
首先是 Node 类 代表链表的一个节点
/* Node class for a linked list */ public class Node<E>{ private E data; private Node<E> next; public Node(E data, Node<E> next){ this.data = data; this.next = next; } public void setData(E data){this.data = data;} public void setNext(Node<E> next){this.next = next;} public E data(){return data;} public Node<E> next(){return next;}; @Override public String toString(){ return data.toString(); } }
然后是 SinglyLinkedList 类 也就是链表
/* A single linked list. */ public class SinglyLinkedList<E>{ private Node<E> head; private int size; public SinglyLinkedList(){ Node<E> head = null; size = 0; } public SinglyLinkedList(E[] a){ Node<E> current = null; for(E e:a){ if(isEmpty()){ current = new Node<E>(e, null); head = current; size++; }else{ current.setNext(new Node<E>(e, null)); current = current.next(); size++; } } } public int size(){return size;} public boolean isEmpty(){return size==0;} public void addLast(E data){ if(isEmpty()){ head = new Node<E>(data, null); }else{ Node<E> tail = findLast(); tail.setNext(new Node<E>(data,null)); tail = tail.next(); } size++; } public void addFirst(E data){ if(isEmpty()){ head = new Node<E>(data, null); }else{ Node<E> node = new Node<E>(data, head); head = node; } size++; } public E peek(){ if(isEmpty()) return null; return head.data(); } public E poll(){ if(isEmpty()) return null; E result = head.data(); head = head.next(); size--; return result; } void increaseSize(){size++;} void decreaseSize(){size--;} Node<E> findLast(){ if(isEmpty()) return null; Node<E> current = head; while(current.next()!=null) current = current.next(); return current; } Node<E> findFirst(){ if(isEmpty()) return null; return head; } void setHead(Node<E> head){this.head = head;} void setSize(int size){this.size = size;} @Override public String toString(){ if(isEmpty()) return null; StringBuilder result = new StringBuilder(); Node<E> runner = head; while(runner.next()!=null){ E data = runner.data(); result.append(data+" "); runner = runner.next(); } result.append(runner.data()); return result.toString(); } }