class Solution {
public ListNode deleteNode(ListNode head, int val) {
ListNode node = head,per=null;
if(head.val == val)
head = head.next;
else{
while(node!=null){
if(node.val == val){
per.next = node.next;
}
per = node;
node = node.next;
}
}
return head;
}
}
leetcode 评论区大佬还提供了一种思路用递归
由于倒数第k个节点说明最后输出的链表长度为k
设置双节点 latter ,former向后移动,当former为空时,latter就是结果
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode former = head,latter=head;
for(int i=0;i<k-1;i++){
former = former.next;
}
while(former.next!=null){
former = former.next;
latter = latter.next;
}
return latter;
}
}
|