链表倒数第n个节点

来源:互联网 发布:go 并发编程 编辑:程序博客网 时间:2024/04/28 12:28

问题描述:

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

样例:

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

思路:

遍历得到链表的总长度,总长度减去n,就可以得到它在正数第几个。

代码:

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @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) {
       int count=0;
       ListNode *dummy=head;
       while(head!=NULL){
           head=head->next;
           count++;}  //得到链表的长度
       for(int i=0;i<count-n;i++){
       dummy=dummy->next;
        }
       return dummy;
        // write your code here
    }
};

个人感悟:

       此题相较于删除倒数第n个节点较简单,思路清晰即可。

0 0