链表中倒数第k个结点

xiaoxiao2021-02-27  387

输入一个链表,输出该链表中倒数第k个结点。


解法一:

if(head==null||k<=0)return null; ListNode nodePre=head; ListNode nodeLast=head; for(int i=1;i<k;i++){ if(nodePre.next!=null)nodePre=nodePre.next; else return null; } while(nodePre.next!=null){ nodePre = nodePre.next; nodeLast=nodeLast.next; } return nodeLast;

解法二:

public ListNode FindKthToTail(ListNode head, int k) { if(k<=0) { return null; } List<ListNode> list = new List<ListNode>(); while (head!=null) { list.Add(head); head = head.next; } int count =list.Count; if (count > 0&&count-k>=0) //注意边界条件呀!!! { return list[count - k]; } else { return null; } }
转载请注明原文地址: https://www.6miu.com/read-5842.html

最新回复(0)