求單鏈表倒數第K個值
題目:
找出單鏈表的倒數第K個元素,比如給定單鏈表:1->2->3->4->5,則鏈表的倒數第2個元素為4
-
思路
-
代碼實現
public class LNode {
int data; //數據域
LNode next; //下一個節點的引用
}
2、順序遍歷兩遍就是,第一次遍歷求出鏈表的整個長度n,第二次遍歷求得第n-k+1個元素就是倒數第K個元素,該方法需要對鏈表進行兩次遍歷
3、快慢指針法,就是使用兩個指針,一個快指針,一個慢指針,開始兩個指針指向頭節點,然后快指針移動K個位置,這時候兩個指針之間的距離為K,然后兩個指針同時移動,當快指針指向的節點為null的時候,慢指針所指的節點即為倒數第K個節點
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);
}
}