File tree Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Original file line number Diff line number Diff line change @@ -96,15 +96,43 @@ public:
96
96
JS Code:
97
97
```javascript
98
98
var getKthFromEnd = function(head, k) {
99
+ //特殊情况
99
100
if(!head) return head;
101
+ //初始化两个指针, 定义指针指向
100
102
let pro = head, after = head;
103
+ //先移动绿指针到指定位置
101
104
for(let i = 0; i < k - 1; i++){
102
105
pro = pro.next;
103
106
}
107
+ //两个指针同时移动
104
108
while(pro.next){
105
109
pro = pro.next;
106
110
after = after.next;
107
111
}
112
+ //返回倒数第k个节点
108
113
return after;
109
114
};
110
- ```
115
+ ```
116
+
117
+ Python Code:
118
+
119
+ ``` python
120
+ class Solution :
121
+ def getKthFromEnd (self , head : ListNode, k : int ) -> ListNode:
122
+ # 特殊情况
123
+ if head is None :
124
+ return head
125
+ # 初始化两个指针, 定义指针指向
126
+ pro = head
127
+ after = head
128
+ # 先移动绿指针到指定位置
129
+ for _ in range (k - 1 ):
130
+ pro = pro.next
131
+ # 两个指针同时移动
132
+ while pro.next is not None :
133
+ pro = pro.next
134
+ after = after.next
135
+ # 返回倒数第k个节点
136
+ return after
137
+ ```
138
+
You can’t perform that action at this time.
0 commit comments