public class ListNode<E> { private transient int size = 0; private Entry<E> header = new Entry<E>(null,null); /** * 向表头插入元素 * @param e */ public void add(E e){ Entry<E> newEntry = new Entry<E>(e,header.next); header.next=newEntry; size++; } /** * 删除数据 * @return * @throws Exception */ public E remove() { Entry<E> e= header.next; if(e==null){ return null; }else{ E result=e.item; header.next=e.next; e.next=null; e.item=null; size--; return result; } } public E get(int index){ Entry<E> e=header; for(int i=0;i<=index;i++){ e=e.next; } return e.item; } /** * 单项列表反转 */ public void reverse(){ if(header.next!=null){ Entry<E> pre=header.next;//上一个节点 Entry<E> cur=pre.next;//当前节点 Entry<E> tmp; while(cur!=null){ tmp=cur.next; cur.next=pre; pre=cur; cur=tmp; } header.next.next=null; header.next=pre; } } public int getSize(){ return size; } private static class Entry<E> { E item; ListNode.Entry<E> next; Entry( E element, ListNode.Entry<E> next) { this.item = element; this.next = next; } }}
测试main:
public static void main(String[] args) { ListNode list = new ListNode(); list.add(1); list.add(2); list.add(3); for (int i=0;i<list.getSize();i++){ System.out.print(list.get(i)+" "); } System.out.println(); System.out.println("开始反转++++++++++++++++++"); list.reverse(); for (int i=0;i<list.getSize();i++){ System.out.print(list.get(i)+" "); } }打印结果
java单项链表反转
最新推荐文章于 2022-09-07 05:18:49 发布