有个小需求要求实现一个双向链表的反转于是就有了下边代码:
链表元素结构定义:
package com.util; public class LinkedNode<T>{ private T value; private LinkedNode<T> prev; private LinkedNode<T> next; public LinkedNode(T value, LinkedNode<T> prev, LinkedNode<T> next) { super(); this.value = value; this.prev = prev; this.next = next; } public T getValue() { return value; } public void setValue(T value) { this.value = value; } public LinkedNode<T> getPrev() { return prev; } public void setPrev(LinkedNode<T> prev) { this.prev = prev; } public LinkedNode<T> getNext() { return next; } public void setNext(LinkedNode<T> next) { this.next = next; } }
链表定义:
package com.util; public class LinkedList<T>{ private transient int size=0; private transient LinkedNode<T> first=null; private transient LinkedNode<T> last=null; /** * 添加元素到双向链表头部 * */ public void addFirst(T t){ LinkedNode<T> oldFirst = first; LinkedNode<T> newNode = new LinkedNode<T>(t, null,oldFirst); first = newNode; if (oldFirst == null) last = newNode; else oldFirst.setPrev(newNode); size++; } /** * 将双向链表转化为一元数组:從頭開始循環到尾部。 * */ public Object[] toArray() { Object[] result = new Object[size]; int i = 0; for (LinkedNode<T> node = first; node != null; node = node.getNext()) result[i++] = node.getValue(); return result; } /** * 反轉 * */ public void reverse(){ if(first==null||last==null) return; LinkedNode<T> prev; LinkedNode<T> next; LinkedNode<T> newFirst=null; LinkedNode<T> newLast=null; for (LinkedNode<T> node = first; node != null; node = node.getPrev()){ prev= node.getPrev(); next= node.getNext(); if(node.getPrev()==null){ newLast=node; }else if(node.getNext()==null){ newFirst=node; } node.setNext(prev); node.setPrev(next); } first=newFirst; last=newLast; } }
备注:这里主要实现了三个功能,在链表头部添加元素、toArray函数、反转函数,实际上链表应该包含其他功能:末尾添加元素,插入元素,索引,移除,遍历等。
测试代码:
import com.util.LinkedList; public class LinkedListTest { public static void main(String[] args) { LinkedList<String> list=new LinkedList<String>(); list.addFirst("5"); list.addFirst("3"); list.addFirst("1"); for (Object string : list.toArray()) { System.out.println(string); } System.out.println("-------------------------------開始反轉-------------------------------"); list.reverse(); System.out.println("-------------------------------結束反轉-------------------------------"); for (Object string : list.toArray()) { System.out.println(string); } } }
原文地址:https://www.cnblogs.com/yy3b2007com/p/8902435.html
时间: 2024-11-05 22:05:05