求單鏈表倒數第K個節點


求單鏈表倒數第K個值

題目:

找出單鏈表的倒數第K個元素,比如給定單鏈表:1->2->3->4->5,則鏈表的倒數第2個元素為4


1、單鏈表中的每個節點包含數據和指向下一個節點的指針

public class LNode {
	int data; //數據域
	LNode next;  //下一個節點的引用
}


2、順序遍歷兩遍就是,第一次遍歷求出鏈表的整個長度n,第二次遍歷求得第n-k+1個元素就是倒數第K個元素,該方法需要對鏈表進行兩次遍歷


3、快慢指針法,就是使用兩個指針,一個快指針,一個慢指針,開始兩個指針指向頭節點,然后快指針移動K個位置,這時候兩個指針之間的距離為K,然后兩個指針同時移動,當快指針指向的節點為null的時候,慢指針所指的節點即為倒數第K個節點


4、代碼實現

public class _015 {

	/**
	 * 快慢指針法
	 * @param head 鏈表的頭節點
	 * @param k
	 * @return
	 */
	public static LNode FindLastK(LNode head, int k) {
		if (head == null || head.next == null)
			return head;
		LNode slow, fast;
		slow = fast = head.next;
		int i;
		for (i = 0; i < k && fast != null; ++i) {
			fast = fast.next;
		}
		if (i < k)
			return null;
		while (fast != null) {
			slow = slow.next;
			fast = fast.next;
		}
		return slow;
	}

	//順序遍歷兩遍法
	public static LNode findLastK1(LNode head, int k) {
		if (head == null || head.next == null)
			return head;
		LNode tmpLNode = head.next;
		int n = 0;
		while (head.next != null) {
			n++;
			head = head.next;
		}
		head.next = tmpLNode;
		int t = n - k + 1;
		while (head.next != null) {
			if (t == 0)
				return head;
			t--;
			head = head.next;
		}
		return null;
	}

	/**
	 * 構造一個帶有頭節點的鏈表
	 * head->1->2->3->4->5
	 * @param args
	 */
	public static void main(String[] args) {
		LNode head = new LNode();
		head.next = null;
		LNode tmp = null;
		LNode cur = head;

		for (int i = 1; i < 7; i++) {
			tmp = new LNode();
			tmp.data = i;
			tmp.next = null;
			cur.next = tmp;
			cur = tmp;
		}

		for (cur = head.next; cur != null; cur = cur.next) {
			System.out.print("構造的鏈表:"+cur.data + " ");
		}
		System.out.println();
		System.out.println("快慢指針求得的數值:"+FindLastK(head, 3).data);
		System.out.println("順序遍歷兩遍求得的值:"+findLastK1(head, 3).data);
	}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM