數據結構與算法(JAVA版)6_3:將單鏈表按某值劃分成左邊小、中間相等、右邊大的形式

(1)把鏈表放入數組裏,在數組上做partition(筆試用)

(2)分成小、中、大三部分,再把各個部分之間串起來(面試用)

package com.inspire.chapter6;

public class Code03_SmallerEqualBigger {

	public static class Node {
		public int value;
		public Node next;

		public Node(int v) {
			value = v;
		}
	}

	public static Node listPartition1(Node head, int pivot) {
		if (head == null) {
			return head;
		}
		Node cur = head;
		int i = 0;
		while (cur != null) {
			i++;
			cur = cur.next;
		}
		// 1.分配一個Node型數組
		Node[] nodeArr = new Node[i];
		// 2.將單鏈表中的結點裝進nodeArr中
		cur = head;
		for (i = 0; i < nodeArr.length; i++) {
			nodeArr[i] = cur;
			cur = cur.next;
		}
		// 接下來就是荷蘭國旗問題了
		arrPartition(nodeArr, pivot);
		for (i = 0; i < nodeArr.length - 1; i++) {
			nodeArr[i].next = nodeArr[i + 1];
		}
		nodeArr[i].next = null;
		return nodeArr[0];
	}

	private static void arrPartition(Node[] nodeArr, int pivot) {
		int less = 0;
		int more = nodeArr.length;
		int index = 0;
		while (index < more) {
			if (nodeArr[index].value == pivot) {
				index++;
			} else if (nodeArr[index].value < pivot) {
				swap(nodeArr, index++, less++);
			} else {
				swap(nodeArr, index, --more);
			}
		}
	}

	private static void swap(Node[] nodeArr, int i, int j) {
		Node temp = nodeArr[i];
		nodeArr[i] = nodeArr[j];
		nodeArr[j] = temp;
	}

	private static void printLinkedList(Node head) {
		System.out.println("Linked list:");
		while (head != null) {
			System.out.print(head.value + " ");
			head = head.next;
		}
		System.out.println();
	}

	public static Node listPartition2(Node head, int pivot) {
		Node sH = null;
		Node sT = null;
		Node eH = null;
		Node eT = null;
		Node mH = null;
		Node mT = null;
		Node next = null;
		while (head != null) {
			next = head.next;// next保留下一個結點
			head.next = null;
			if (head.value < pivot) {
				if (sT == null) {
					sH = head;
					sT = head;
				} else {
					sT.next = head;
					sT = head;// sT移向head的位置
				}
			} else if (head.value == pivot) {
				if (eT == null) {
					eH = head;
					eT = head;
				} else {
					eT.next = head;
					eT = head;
				}
			} else {
				if (mT == null) {
					mH = head;
					mT = head;
				} else {
					mT.next = head;
					mT = head;
				}
			}
			head = next;// head指向下一個結點
		}

		if (sT != null) {// 如果小於區的尾指針不爲null
			sT.next = eH;
			eH = eH == null ? sT : eH;
		}
		if (eT != null) {// 如果等於區的尾指針不爲null
			eT.next = mH;
			mH = mH == null ? eT : mH;
		}
		return sT != null ? sH : (eT != null ? eH : mH);
	}

	public static void main(String[] args) {
		Node head1 = new Node(7);
		head1.next = new Node(9);
		head1.next.next = new Node(1);
		head1.next.next.next = new Node(8);
		head1.next.next.next.next = new Node(5);
		head1.next.next.next.next.next = new Node(2);
		head1.next.next.next.next.next.next = new Node(5);
		printLinkedList(head1);
		//head1 = listPartition1(head1, 9);
		head1 = listPartition2(head1, 8);
		printLinkedList(head1);
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章