链表倒序
来源:互联网 发布: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指针指向顺序交换,从而实现链表整体的倒序。
阅读全文
0 0
- 单向链表倒序
- 链表倒序算法
- C链表倒序
- 链表的倒序
- 链表倒序算法
- 链表倒序
- 链表倒序
- 倒序输出链表
- 倒序输出链表
- 关于链表倒序
- 倒序输出链表
- 倒序遍历链表
- 链表倒序输出
- 链表倒序打印
- 链表倒序
- 链表的倒序算法
- c++实现链表倒序
- 递归倒序输出链表
- android下载解析xml
- GPIO口超强总结
- [bzoj4356][ceoi2014] wall
- PS之卡通徽章制作
- docker container DNS配置介绍和源码分析
- 链表倒序
- shell局部变量和全局变量
- js基本操作2
- Unable to find setter method for attribute: [commandName]
- Unity3D热更新之网页运行工具
- 你充满电了吗?——序(笔记)
- 【VS开发】vector<ImageFeatures> features(num_images)析构报错
- Hibernate 工具类(个人编写,初次了解,还未完善)
- PyQt5学习教程17:70行的货币转换程序的编程思路