C语言链表反转完整版

#include 

struct listNode{
    int data;
    struct listNode* next;
};


struct listNode *ReverseList(struct listNode* head)
{
    if (head==NULL || head->next==NULL)
    {
        return head;
    }
    struct listNode *previous=NULL;
    struct listNode *next=NULL;
    while (head !=NULL)
    {
        next=head->next;
        head->next=previous;
        previous=head;
        head=next;
    }
    return previous;
}

void printList(struct listNode* head)
{
    while (head!=NULL)
    {
        printf("%d ",head->data);
        head=head->next;
    }
    printf("\n");
}

void destroyList(struct listNode* head)
{
    if (head==NULL)
    {
        return;
    }
    struct listNode*tmp=head;
    while (head!=NULL)
    {
        tmp=head;
        head=head->next;
        delete tmp;

    }
}
int main()
{
    struct listNode* ln=new listNode{};
    struct listNode* head=ln;
    ln->data=1;
    for (int i=2;i<8;i++)
    {
        ln->next=new listNode{};
        ln=ln->next;
        ln->data=i;
    }
    ln->next=NULL;
    printList(head);
    struct listNode*newHead=ReverseList(head);
    printList(newHead);

    destroyList(newHead);
}

CLion 2020运行结果

/Users/caochenghua/CLionProjects/NavInfo/cmake-build-debug/NavInfo
1 2 3 4 5 6 7 
7 6 5 4 3 2 1 

Process finished with exit code 0

你可能感兴趣的:(编程经验,面试,c语言)