例如:
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。
方法一:或许链表长度,依次向后遍历len/2步
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
int steps = size(head)/2;
ListNode cur = head;
for(int i = 0;i < steps;i++){
cur = cur.next;
}
return cur;
}
public int size(ListNode head){
int size = 0;
for(ListNode cur = head;cur != null;cur = cur.next){
size++;
}
return size;
}
}
方法二:快慢指针
fast一次向后走两步。
slow一次向后走一步。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
if(head == null || head.next == null){
//只有一个节点或者无节点的时候,直接返回。
return head;
}
ListNode fast = head;
ListNode slow = head;
for(ListNode cur = head; cur != null; cur = cur.next){
fast = fast.next.next;
slow = slow.next;
if(fast == null || fast.next == null){
return slow;
}
}
return slow;
}
}
输入一个链表,输出该链表中倒数第k个结点。
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(k <=0 || k > size(head) || head == null){
return null;
}
int steps = size(head) - k;
ListNode cur = head;
for(int i = 0;i < steps;i++){
cur = cur.next;
}
return cur;
}
public int size(ListNode head){
int size = 0;
for(ListNode cur = head;cur != null;cur = cur.next){
size++;
}
return size;
}
}