1. 程式人生 > >資料結構基礎------1.線性表之單鏈表的建立與輸出方法(Java版)

資料結構基礎------1.線性表之單鏈表的建立與輸出方法(Java版)

基礎知識:

  1. 線性表(linear list),是其組成元素間具有線性關係的一種線性結構。
  2. 線性表有 ①順序儲存結構(sequential storage structure) 順序儲存結構可以簡單的理解利用為 陣列 的形式來進行儲存資料。 ②鏈式儲存結構(chained storage structure) 鏈式儲存結構中包括 單鏈表 和 雙鏈表

注意:順序陣列必須保證邏輯關係(logical relationship)和儲存關係(storage relationship)必須連續。

下面就介紹關於單鏈表的建立與輸出方法:

package practice;
import java.util.*;
class Node			//建一個連結串列類
{
	public int data;			//設定一個簡單的內部元素
	Node next;
	//********新建連結串列*******
	public static Node creat(int n)
	{
		Scanner input = new Scanner(System.in);
		Node head = null, p = null, q = null;	//頭結點初始化
		for(int i = 0; i < n; i++)
		{
			p = new Node();						//這一步很重要!為下一個結點申請新的空間,否則就會報空指標的錯誤!
			p.data = input.nextInt();
			if(head == null) head = p;		//保證了頭結點的內容不為空
			else q.next = p;						//向後延續
			q = p;		
		}
		q.next = null;								//這一步也很重要,保證了最後一個結點的下個結點為null,以便其他方法的實現
		input.close();
		return head;
	}
	//********輸出連結串列********
	public static void put(Node head)	//傳入頭結點
	{
		Node p = head;
		while(p != null)							//注意判斷條件
		{
			System.out.print(p.data+"	");
			p = p.next;							//下一個結點
		}
	}
	//******連結串列計數器*******
	public static int length(Node head)  //連結串列計數器的原理和輸出連結串列一樣
	{
		int l = 0;
		Node p = head;
		while(p != null)
		{
			l++;
			p = p.next;
		}
		return l;
	}
}
public class Line 
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		//新建一個連結串列
		System.out.println("請輸入新建連結串列的長度");
		int n = input.nextInt();
		System.out.println("請輸入連結串列中資料:");
		Node head1 = Node.creat(n);
		Node.put(head1);
		System.out.println();
		System.out.println("計算該連結串列的長度為:" + Node.length(head1));
		input.close();
	}
}

上述單鏈表的操作涉及到三個量,head,p,q

head 是作為連結串列的索引,一旦單鏈表在操作過程中head丟失,那麼這個連結串列也就丟失了 p 通常用來執行下一個結點的相關操作(比如傳入資料等) q通常用來建立新節點與上一個結點的指向關係 具體的關係如下: 在這裡插入圖片描述