1. 题目分析
这道题主要是有两种思想。
- 基本思想1:
- 我们需要的是返回后k个节点,这让我第一时间联想到了栈的性质
- 设置两个栈,就能解决,下面给出图解
准备好我们需要的变量
- 基本思想2:
- 就是我们经常用的双指针,而且是同步的双指针
- 给出图解
在这里,我们用栈的方法来实现。
2. 代码实现
2.1. Python代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getKthFromEnd(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
stack = []
cur = head
while cur != None:
stack.append(cur)
cur = cur.next
print(stack)
cur = ListNode(0)
new_head = cur
for i in stack[-k:]:
cur.next = i
cur = cur.next
return new_head.next
2.2. Java代码
/**
* 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) {
Stack stack1 = new Stack();
Stack stack2 = new Stack();
ListNode cur = new ListNode(0);
while(head != null){
stack1.add(head);
head = head.next;
}
head = cur;
int n = k;
for(int i = 0;i < n;i++){
stack2.add(stack1.pop());
}
for(int i = 0;i < n;i++){
cur.next = (ListNode)stack2.pop();
cur = cur.next;
}
return head.next;
}
}