需要考慮因素,高效應權衡多方面因素
01. 先學著實現一個簡單的Java版的單項鏈表
構建任意長度的任意數值的鏈表, 頭插法,順序遍歷輸出鏈表
package com.szs.list;
/**
* 單鏈表
* @author Administrator
*
*/
public class MyLinkedList {
public int data;
public MyLinkedList next;
public MyLinkedList(int data) {
this.data=data;
this.next=null;
}
public MyLinkedList() {
this.data=-1;
this.next=null;
}
}
02.編寫上面的單項鏈表的逆序輸出
高效的輸出鏈表,直接使用棧來存儲~~
package com.szs.list;
import java.util.Random;
import java.util.Stack;
public class InverseSingleList {
public static void main(String[] args) {
MyLinkedList head= new MyLinkedList();
createList(head);
inverseList(head);
}
/**
* 構建任意長度的任意數值的鏈表, 頭插法
*/
public static void createList(MyLinkedList head) {
Random random = new Random(System.currentTimeMillis());
int len = random.nextInt(10);
for(int i=0;i<len;i++) {
int data = random.nextInt(100);
MyLinkedList next = new MyLinkedList(data);
next.next = head.next;
head.next = next;
}
/**
* 順序遍歷輸出鏈表
*/
MyLinkedList head2 = head.next;
System.out.println("順序");
while(head2!=null) {
System.out.print(head2.data+"\t");
head2=head2.next;
}
System.out.println("length="+len);
}
/**
* 高效的輸出鏈表,使用棧來存儲
*/
public static void inverseList(MyLinkedList head) {
MyLinkedList head2 = head.next;
Stack<Integer> stack = new Stack<>();
System.out.println("逆序");
while(head2!=null) {
stack.push(head2.data);
head2=head2.next;
}
while(!stack.isEmpty()) {
System.out.print(stack.pop()+"\t");
}
}
}
03.進行測試
順序
25 69 10 28 23 89 32 2 23 length=9
逆序
23 2 32 89 23 28 10 69 25
-------
順序
28 35 83 99 88 length=5
逆序
88 99 83 35 28
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。