<span style="font-family:KaiTi_GB2312;font-size:18px;"><strong> 线性表一章基本看完了,但是感觉还学得太少,应该和一些经典的算法相结合,看看自己应用的如何。不得不承认自己只是做简单的实现,并没有对代码进行太多的优化。。。希望各位大神莫怪~~废话少说,代码搞起。。</strong></span>
<strong><span style="font-family:KaiTi_GB2312;font-size:18px;">//有序链表的合并 class MergerSingleList { private Nod head; public Nod getHead() { return head; } public void setHead(Nod head) { this.head = head; } public Nod getTail() { return tail; } public void setTail(Nod tail) { this.tail = tail; } // 查找指定位置的结点 public Nod FindKth(int k) { Nod temp = head; int i = 1; while (temp != null && i < k) { // 移动元素,直到找到相应位置 temp = temp.next; i++; } if (i == k) return temp; else return null; } // 将结点插入指定位置 public void insert(int index, int a) { Nod newNode = new Nod(a); if (index > Length + 1) { System.out.println("超出范围,无法插入"); } else { if (index == 1) { newNode.next = head; head = newNode; Length++; } else if (index > 1 && index < 100) { newNode.next = FindKth(index - 1).next; FindKth(index - 1).next = newNode; Length++; } } } // 打印链表 public void display() { Nod current = head; while (current != null) { current.displayNod(); current = current.next; } } // Sort public void BubbleSort(MergerSingleList m1) { Nod current1 = null; Nod current2 = null; int temp = 0; for (int k = m1.Length - 1; k > 0; k--) { for (int i = 1; i < k + 1; i++) { if (i <= m1.Length) { current1 = m1.FindKth(i); current2 = m1.FindKth(i + 1); if (current1.key > current2.key) { temp = current1.key; current1.key = current2.key; current2.key = temp; } } } } m1.display(); } public static void main(String args[]) { MergerSingleList ms1 = new MergerSingleList(); MergerSingleList ms2 = new MergerSingleList(); // 在单链表1中插入元素 ms1.insert(1, 1); ms1.insert(2, 2); ms1.insert(3, 3); ms1.insert(4, 8); ms1.insert(5, 9); // 在单链表2中插入元素 ms2.insert(1, 4); ms2.insert(2, 5); ms2.insert(3, 6); ms2.insert(4, 7); ms2.insert(5, 7); // 打印单链表1、2 System.out.println("单链表1"); ms1.display(); System.out.println(); System.out.println("单链表2"); ms2.display(); System.out.println(); /** ************************方法1************************** */ // ms1.FindKth(ms1.Length).next = ms2.head; // System.out.println("单链表合并后为:"); // ms1.display(); /** ************************方法2************************** */ // 建立单链表3,存放单链表1、2的元素 MergerSingleList ms3 = new MergerSingleList(); for (int i = 0; i <= (ms1.Length + ms2.Length); i++) { ms3.insert(i, 0); } System.out.println("单链表3"); ms3.display(); System.out.println(); ms3 = ms1; System.out.println("将单链表1存放到单链表3后"); ms3.display(); System.out.println(); for (int j = 1; j <= ms2.Length; j++) { int a = ms2.FindKth(j).key; ms3.insert(ms1.Length + 1, a); } System.out.println("合并的链表"); ms3.display(); System.out.println(); System.out.println("排序后的链表"); ms3.BubbleSort(ms3); } } class Nod { public int key; public Nod next; // 初始化头结点 public Nod(int head) { this.key = head; this.next = null; } public void displayNod() { System.out.print(key + " -> "); } } </span></strong>
时间: 2024-10-11 11:44:18