1. 程式人生 > >鏈表倒數第k個節點

鏈表倒數第k個節點

stream malloc end alloc sizeof size clu AC list

題目:輸入一個鏈表,輸出該鏈表中倒數第k個結點

思路:1.遍歷兩遍鏈表,第一遍找到鏈表長度n,第二遍從0到n-k+1找到倒數第k個節點,不是最優解。

   2.使用兩個指針,只需遍歷一遍鏈表。第一個指針先走k-1步,然後兩個指針同時向後遍歷,當第一個指針走到尾節點時,第二個指針剛好在倒數第k個節點上。

註意:代碼的魯棒性!!

   鏈表為空,k為0,k大於鏈表長度的情況下應該返回NULL

思路1

#include <iostream>
#include <malloc.h>
using namespace std;

typedef struct Node
{
    int
val; struct Node* next; }ListNode; ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { if(pListHead == NULL || k == 0)return NULL; ListNode* p = pListHead; ListNode* q = pListHead; int count = 0; while(p->next != NULL) { p = p->next; count
++; } int n = count-k+1; if(n <= 0)return NULL; for(int i = 0;i < n;i++) { q = q->next; } return q; } int main() { int n,num; ListNode* pHead = (ListNode*)malloc(sizeof(ListNode)); pHead->next = NULL; cin>>n; ListNode* pTail = pHead;
while(n--) { ListNode* p = (ListNode*)malloc(sizeof(ListNode)); cin>>num; p->val = num; p->next = NULL; pTail->next = p; pTail = p; } ListNode* node = FindKthToTail2(pHead,3); cout<<node->val<<endl; }

思路2

#include <iostream>
#include <malloc.h>
using namespace std;

typedef struct Node
{
    int val;
    struct Node* next;
}ListNode;

ListNode* FindKthToTail2(ListNode* pListHead, unsigned int k) {
    if(pListHead == NULL || k == 0)return NULL;
    ListNode* pAhead = pListHead;
    ListNode* pBehind = pListHead;
    for(unsigned int i = 0;i < k-1;i++)
    {
        if(pAhead->next != NULL)
            pAhead = pAhead->next;
        else{
            return NULL;
        }
    }
    while(pAhead->next != NULL)
    {

        pAhead = pAhead->next;
        pBehind = pBehind->next;
    }
    return pBehind;
}

int main()
{
    int n,num;
    ListNode* pHead = (ListNode*)malloc(sizeof(ListNode));
    pHead->next = NULL;
    cin>>n;
    ListNode* pTail = pHead;
    while(n--)
    {
        ListNode* p = (ListNode*)malloc(sizeof(ListNode));
        cin>>num;
        p->val = num;
        p->next = NULL;
        pTail->next = p;
        pTail = p;
    }
    ListNode* node = FindKthToTail2(pHead,3);
    cout<<node->val<<endl;
}

鏈表倒數第k個節點