题目:

链表倒数第n个节点

找到单链表倒数第n个节点,保证链表中节点的最少数量为n。

样例

给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.

解题:

某年408计算机考研题目

Java程序:

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: Nth to last node of a singly linked list. 
     */
    ListNode nthToLast(ListNode head, int n) {
        // write your code here
        if(head ==null)
            return null;
        if( head.next ==null && n==1)
            return head;
        ListNode p = head;
        ListNode current = new ListNode(0);
        current.next = head;
        while( p.next!=null){
            if(n>1){
                p = p.next;
                n --;
            }else{
                p = p.next;
                current = current.next;
                
            }
        }
        return current.next;
    }
}
View Code

总耗时: 2548 ms

Python程序:

 

相关文章:

  • 2022-02-16
  • 2021-09-18
  • 2021-06-15
  • 2021-09-08
  • 2021-05-30
  • 2021-12-31
  • 2021-10-09
  • 2021-05-10
猜你喜欢
  • 2022-12-23
  • 2021-11-06
  • 2021-06-18
  • 2021-06-20
  • 2021-12-17
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案