題目描述
輸入一個鏈表,輸出該鏈表中倒數第k個結點。
思路:首先統計鏈表中結點的個數 爲N,如果小於K則返回NULL,否則輸出第N-K個節點,即倒數第K個節點
代碼如下:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
ListNode list = head;
int count = 0;
while(list != null){
count++;
list = list.next;
}
if(k>count)return null;
ListNode p = head;
for(int i = 0;i<count -k;i++){
p = p.next;
}
return p;
}
}
題目描述
輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
思路:關鍵在於聲明一個結點preNode用來記錄前一個結點,使下一次循環時的結點的next指向它,反轉順序。
代碼如下:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.Stack;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null)return head;
ListNode preNode = null;
while(head != null){
ListNode node = head.next;
head.next = preNode;
preNode = head;
head = node;
}
return preNode;
}
}
題目描述
輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,當然我們需要合成後的鏈表滿足單調不減規則。
思路:聲明一個新鏈表,比較原來兩個鏈表的 val 值,小的插入新鏈表即可。最後將沒有比較的完的鏈表中的節點插入新鏈表
代碼:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode node = new ListNode(-9999);
ListNode tmp = node;
while(list1 != null && list2 != null){
if(list1.val > list2.val){
tmp.next = list2;
list2 = list2.next;
}else{
tmp.next = list1;
list1 = list1.next;
}
tmp = tmp.next;
}
if(list1 != null)tmp.next = list1;
if(list2 != null)tmp.next = list2;
return node.next;
}
}