实现一种算法,找出单向链表中倒数第k个节点,返回该节点的值;
示例:
输入: 1->2->3->4->5 和 k = 2
输出: 4
分析: 可以先遍历一遍链表,计算链表的长度;然后根据正反向关系就可以得到节点;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int kthToLast(ListNode* head, int k) {
//先遍历一遍链表,获取长度
int len = 0;
ListNode *cur = new ListNode();
cur = head;
while(cur!=NULL){
len++;
cur = cur->next;
}
//len-k+1
ListNode *cur1 = new ListNode();
cur1 = head;
for(int i = 0; i<len-k; i++){
cur1 = cur1->next;
}
return cur1->val;
}
};
分析: 类似滑动窗口思想;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int kthToLast(ListNode* head, int k) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *pre= new ListNode(0);
ListNode *cur = new ListNode(0);
pre = dummy;
cur = dummy;
for(int i = 0; i<k; i++){
cur = cur->next;
}
while(cur!=NULL){
pre = pre->next;
cur = cur->next;
}
return pre->val;
}
};

本文介绍了一种算法,用于找出单向链表中倒数第k个节点并返回其值。通过两次遍历链表,首先计算链表的长度,然后根据长度和k值找到目标节点。此外,还提供了一种使用滑动窗口思想的优化方法,仅需一次遍历即可完成。
311





