1、創建鏈結構實體Node
/** * 鏈表結構實體類 */ public class Node { Node next = null; //下一節點 int data; //節點數據 public Node(int data) { this.data = data; } }
2、鏈表的操作(鏈表的頭結點創建、增加元素,刪除元素、求鏈表長度、根據輸入數據求下標)
/** * 鏈表功能實現 */ public class Linked_List { Node head = null; //鏈表頭結點 /** * 1、求鏈表長度:以備后續用 * 思路:遍歷一個節點,記錄長度加一(注意:初始長度給0) * * @return int:返回長度 */ public int get_length() { int list_length = 0; Node cur_node; cur_node = head; while (cur_node != null) { list_length++; cur_node = cur_node.next; } return list_length; } /** * 2、添加 * 思路:找到鏈表的末尾節點,把新的數據節點添加在后面 * * @param date :插入的數據 */ public void add_Node(int date) { Node newnode = new Node(date); if (head == null) { //判斷是否只有一個頭結點 head = newnode; return; } else { Node temp = head; while (temp.next != null) { //不為頭節點,找到最后一個節點 temp = temp.next; } temp.next = newnode; } } /** * 3、刪除 * 思路:傳入下標,根據下標,找到相應的節點,刪除節點的前一節點指向刪除節點下一節點 * * @param index:刪除的數據的下標 * @return */ public boolean delete_Node(int index) { if (index < 1 || index > get_length()) { System.out.println("你所要刪除的元素下標輸入有問題"); return false; } if (index == 1) { head = head.next; return true; } Node pre_node = head; Node cur_node = pre_node.next; int i = 2; while (pre_node != null) { if (i == index) { pre_node.next = cur_node.next; return true; } else { pre_node = pre_node.next; cur_node = cur_node.next; i++; } } return true; } /** * 4、根據輸入數據求下標 * @param data:輸入的數據 * @return int:返回輸入數據下標 */ public int get_data(int data) { Node node = head; int index = 0; while (node != null){ if (node.data == data){ return index; } node = node.next; index++; } return -1; } /** * 5、打印顯示輸出 */ public void print_linklist() { Node node = head; while (node != null) { System.out.print(node.data + " "); node = node.next; } System.out.println(); } public static void main(String[] args) { //1、創建鏈表 Linked_List linked_list = new Linked_List(); //2、添加鏈表元素 linked_list.add_Node(4); linked_list.add_Node(8); linked_list.add_Node(7); linked_list.add_Node(1); //3、打印添加的元素 linked_list.print_linklist(); //4、刪除下標元素 linked_list.delete_Node(4); linked_list.print_linklist(); //5、獲取鏈表長度 System.out.println("鏈表長度 "+ linked_list.get_length()); int index = linked_list.get_data(1); if (index == -1){ System.out.println("你要查找的數據不存在"); }else{ System.out.println("你要查找的數據元素下標 " + index); } } }
3、實現結果小測試
4 8 7 1 4 8 7 鏈表長度 3 (1被刪除,長度減一) 你要查找的數據不存在 (由於1已被刪除,所有在main中求1的下標不在)