Lintcode -链表倒数第n个节点

来源:互联网 发布:乐高ev3编程视频教程 编辑:程序博客网 时间:2024/06/06 03:17

描述

找到单链表倒数第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;    }
原创粉丝点击