LeetCode(剑指 Offer)- 22. 链表中倒数第k个节点
Posted 放羊的牧码
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(剑指 Offer)- 22. 链表中倒数第k个节点相关的知识,希望对你有一定的参考价值。
题目链接:点击打开链接
题目大意:略
解题思路:略
相关企业
- 字节跳动
AC 代码
- Java
/**
* Definition for singly-linked list.
* public class ListNode
* int val;
* ListNode next;
* ListNode(int x) val = x;
*
*/
// 解决方案(1)
class Solution
public ListNode getKthFromEnd(ListNode head, int k)
int len = 0;
ListNode cur = head;
while (cur != null)
len++;
cur = cur.next;
k = len - k;
for (int i = 0; i < k; i++)
head = head.next;
return head;
// 解决方案(2)
class Solution
public ListNode getKthFromEnd(ListNode head, int k)
ListNode former = head, latter = head;
for(int i = 0; i < k; i++)
former = former.next;
while(former != null)
former = former.next;
latter = latter.next;
return latter;
- C++
/**
* Definition for singly-linked list.
* struct ListNode
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL)
* ;
*/
class Solution
public:
ListNode* getKthFromEnd(ListNode* head, int k)
ListNode *former = head, *latter = head;
for(int i = 0; i < k; i++)
former = former->next;
while(former != nullptr)
former = former->next;
latter = latter->next;
return latter;
;
以上是关于LeetCode(剑指 Offer)- 22. 链表中倒数第k个节点的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode刷题100天—剑指 Offer 22. 链表中倒数第k个节点(链表)—day26
Leetcode刷题100天—剑指 Offer 22. 链表中倒数第k个节点(链表)—day26
LeetCode Java刷题笔记—剑指 Offer 22. 链表中倒数第k个节点