Lintcode -链表倒数第n个节点

描述

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

样例

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

常规解法(解法一)

思路:计算单链表长度Length,然后遍历单链表找出第(Length-n+1)个结点

代码实现

耗时:54ms

ListNode *nthToLast(ListNode *head, int n) {
        if(head == NULL)
            return NULL;
        if(head->next == NULL && n == 1)
            return head;
        int length, number;
        length = 0;
        number = 1;
        ListNode *p, *q;
        p = head;
        q = head;
        while(p != NULL){
            length++;
            p = p->next;
        }
        while(1){
            if(number == length-n+1){
                return q;
                break;
            }
            number++;
            q = q->next;
        }
    }

常规解法(解法二)

思路:将单链表反转,找到正数第n个结点
耗时:61ms

代码实现

ListNode *nthToLast(ListNode *head, int n) {
        if (head == NULL)
            return NULL;
        if (head->next == NULL && n == 1)
            return head;
        head = reverse(head);
        int count = 1;
        ListNode *r;
        r = head;
        while (r != NULL) {
            if (count == n) {
                return r;
                break;
            }
            count++;
            r = r->next;
        }
    }
private:
    ListNode *reverse(ListNode *head) {
        ListNode *p, *q;
        p = head->next;
        while (p->next != NULL) {
            q = p->next;
            p->next = q->next;
            q->next = head->next;
            head->next = q;
        }
        p->next = head;
        head = head->next;
        p->next->next = NULL;
        return head;
    }
};

一次遍历法(解法三)

思路:定义两个指针fast和slow,fast指针先移动到第N-1个结点,然后fast和slow指针同时向后移动。直到fast指针只想尾结点。此时,slow指针指向的位置即为倒数第n个节点;
耗时:81ms

ListNode *nthToLast(ListNode *head, int n) {
        if(head == NULL)
            return NULL;
        if(head->next == NULL && n == 1)
            return head;
       ListNode *fast, *slow;
       fast = head;
       slow = head;
       int i;
       for(i=0; i<n-1; i++){
           fast = fast->next;
       }
       while(fast->next != NULL){
           slow = slow->next;
           fast = fast->next;
       }
       return slow;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值