链表中倒数第K个节点
方法一
双指针法,两个指针相距k,当右指针移动到最后一个元素,此时左指针对应的是倒数第k个元素
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* getKthFromEnd(struct ListNode* head, int k){
struct ListNode* tail = head;
if(!head){
return head;
}
//当k为1时不进入循环
while(--k){
tail = tail->next;
}
while(tail->next){
tail = tail->next;
head = head->next;
}
return head;
}
方法二
遍历得到链表长度n,再次遍历到n-k+1时,返回节点地址。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int GetLen(struct ListNode* head){
int cnt = 0;
while(head){
cnt++;
head = head->next;
}
return cnt;
}
struct ListNode* getKthFromEnd(struct ListNode* head, int k){
int len = GetLen(head);
len = len-k+1;
while(--len){
head = head->next;
}
return head;
}
还可以通过栈,哈希表解决。但是较优解是快慢指针。