剑指offer --链表

来源:互联网 发布:韩国人的生活水平知乎 编辑:程序博客网 时间:2024/05/16 14:37
#include <iostream>#include <stack>#include <stdio.h>using namespace std;struct Node{    int value;    Node* next;    Node(int v):value(v){}};void InsertList(Node *head,int key){    Node* NewNode = new Node(key);    NewNode->next=nullptr;    if(head==nullptr)    {        head=NewNode;    }    else    {        Node *pNode=head;        while(pNode->next!=nullptr)        {            pNode=pNode->next;        }        pNode->next=NewNode;    }}void PrintList(Node *head){    Node *pNode=head;    if(pNode==nullptr)        printf("empity list!!");    else    {        while(pNode->next!=nullptr)        {            printf("%d->",pNode->value);            pNode=pNode->next;        }        printf("%d\n",pNode->value);    }}void PrintListReversingly(Node *head){    stack<Node*> nodes;    Node *pNode=head;    if(pNode==nullptr)    {        printf("empty list!!!");    }    else    {        while(pNode->next!=nullptr)        {            nodes.push(pNode);            pNode=pNode->next;        }        nodes.push(pNode);    }    while(!nodes.empty())    {        pNode=nodes.top();        printf("%d->",pNode->value);        nodes.pop();    }    printf("\n");}Node* FindKthToTail(Node *head,int k){    if(head==nullptr||k==0)    {        return nullptr;    }    Node* pAhead = head;    Node* pBhead = nullptr;    for(int i=0;i<k-1;i++)    {        if(pAhead->next!=nullptr)        {            pAhead=pAhead->next;        }        else            return nullptr;    }    pBhead=head;    while(pAhead->next!=nullptr)    {        pAhead=pAhead->next;        pBhead=pBhead->next;    }    return pBhead;}int main(){  Node *head1=nullptr;  head1 = (Node *)malloc(sizeof(Node));  InsertList(head1,1);  InsertList(head1,2);  InsertList(head1,3);  InsertList(head1,3);  InsertList(head1,3);  InsertList(head1,3);  PrintList(head1);  PrintListReversingly(head1);  Node *target = FindKthToTail(head1,5);  printf("%d\n",target->value);}

0 0
原创粉丝点击