22. 链表中倒数第k个节点
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
int count = 0;
ListNode l = head;
while(l != null){
count++;
l = l.next;
}
for(int i = 0; i < count- k; ++i){
head = head.next;
}
return head;
}
}
改进:
算法思想:
定义两个指针。第一个指针指向第k个节点时,第二个指针指向第一个节点,那么当第一个指针指向最后一个节点时,第二个指针指向的就是倒数第k个节点。这样只用遍历一次就可以找到所求节点。
代码:
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
if(head == null || k == 0){
return null;
}
ListNode former = head, later=head;
for(int i = 0; i < k; ++i){
if(former == null){
return null;
}
former = former.next;
}
while(former != null){
former = former.next;
later = later.next;
}
return later;
}
}
注意:
要考虑以下几种情况来保证程序的健壮性:
1.输入的head为空指针;
2.输入的链表节点总数小于k;
3.输入的参数k为0。
24. 反转链表
代码:
头插法
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode l = head;
ListNode l2 = head.next;
l = l2;
l2 = l2.next;
l.next = head;
head.next = null;
while(l2 != null){
head = l;
l = l2;
l2 = l2.next;
l.next = head;
}
return l;
}
}
改进:
迭代法
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while(curr != null){
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}