1. 链表中倒数第k个节点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode findKthToTail(ListNode pListHead, int k) {
if(pListHead == null) return null;
ListNode tmp = pListHead;
int len = 0;
while(tmp != null) {
len ++;
tmp = tmp.next;
}
len = len - k;
if(len < 0) return null;
for(int i = 0; i < len; i ++) {
pListHead = pListHead.next;
}
return pListHead;
}
}
2. 旋转链表
思路: 一道简单的模拟, 注意链表题目的边界条件和节点处理, 链表题目思路一般比较好写, 但是代码容易出NullPoniterException, 所以不要因为会思路了就不敲代码.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null || head.next == null) return head;
int len = 0;
ListNode tmpHead = head;
while(head != null) {
len ++;
head = head.next;
}
k = k % len;
if(k == 0) return tmpHead;
len = len - k - 1;
head = tmpHead;
for(int i = 0; i < len; i ++) {
head = head.next;
}
ListNode tail = head.next;
ListNode res = tail;
while(tail.next != null) tail = tail.next;
tail.next = tmpHead;
head.next = null;
return res;
}
}