链表倒序

来源:互联网 发布:it专业 编辑:程序博客网 时间:2024/06/08 10:39
#include <iostream>#include <malloc.h>using namespace std;typedef struct Node{    int data;    struct Node* next;//是创建一个指向后一个节点的指针 这个指针所指向的内容仍然是一个struct Node结构体} Node;Node * List = NULL;void make_list(int list_len){    int LIST_LEN=0;    LIST_LEN=list_len;    List = (Node *)malloc(sizeof(Node) * LIST_LEN);//分配可以存放LIST_LEN长度的内存    //(Node *)为强制转为类型,由于malloc为void类型,不强制改为相同类型在部分编译器中容易报错    int i = 0;    int n=0;    for(i = 0; i < (LIST_LEN); i++)    {        cin>>n;        (List + i)->data = n;        (List + i)->next = List + i + 1;    }    (List + LIST_LEN -1)->next = NULL;//终止末尾指针}void print_list(){    Node * cur = List;    while(cur!=NULL)    {        cout << cur->data<<endl;        cur = cur->next;    //cur得到下一个地址    }    cout<<endl;}void fanXiang(Node*list){    Node *old_head=NULL;    Node *new_head=NULL;    Node *cur=list;    while(cur!=NULL)    {        old_head=cur->next;        cur->next=new_head;        new_head=cur;        cur=old_head;    }    List=new_head;}int main(){    int list_len=0;    cout<<"请输入链表长度:";    cin>>list_len;    make_list(list_len);    fanXiang(List);    print_list();    return 0;}
为了更详细的了解链表在倒序时的工作原理,我在
void make_list(int list_len);和

void fanXiang(Node*list);中进行了小小的修改,使其可以让我看见其中的工作。

void make_list(int list_len){    int LIST_LEN=0;    LIST_LEN=list_len;    List = (Node *)malloc(sizeof(Node) * LIST_LEN);    int i = 0;    int n=0;    for(i = 0; i < (LIST_LEN); i++)    {        cin>>n;        (List + i)->data = n;        (List + i)->next = List + i + 1;        cout << "List + i->data的地址" << &(List +i)->data<<endl;//新加行        cout << "List + i->next的地址" << (List+i)->next<<endl;//新加行    }    (List + LIST_LEN -1)->next = NULL;//终止末尾指针}



void fanXiang(Node*list){    Node *old_head=NULL;    Node *new_head=NULL;    Node *cur=list;    while(cur!=NULL)    {        old_head=cur->next;        cout << "old_head1 " << old_head << "   cur->next1 " << cur->next << endl;//新加行        cur->next=new_head;        cout << "cur->next2 " << cur->next << "   new_head1 " << new_head << endl;//新加行        new_head=cur;        cout << "new_head2 " << new_head << " cur " << cur << endl;//新加行        cur=old_head;        cout << "cur2 " << cur << endl;//新加行    }    List=new_head;}

运行结果:


可以通过运行结果看出倒序的工作原理实质就是地址之间的交换,
将原链表中的next指针指向顺序交换,从而实现链表整体的倒序。

原创粉丝点击