单链表逆序 也叫反转
来源:互联网 发布:c语言程序停止运行 编辑:程序博客网 时间:2024/05/17 22:00
I have browsed many codes about the list reversed, most of which are hard to understand and complicated;
to reverse a single list, two methods can be required:
1; create a another list from the old list reversed, that is to say the new nodes are coming from the tail of the old list.
2; reverse the pointer; we need only to reverse the pointer from next to prior;
so we found the last method are better than first , because it is terse and without allocating new memory;
for example, original order is following:
prior cur next
○->○->○
reverse
○<-○<-○
ok, principle is easy to understand, implement it
#includeusing namespace std;struct Node{int data;struct Node *next;};struct Node *createList(const int & aiNum){struct Node *head = NULL;struct Node *newPtr = NULL;struct Node *cur;int i = 0;for (; i < aiNum; i++ ){if (!head){head = (struct Node*)malloc(sizeof(Node));head->data = i;head->next = NULL;cur = head;}else{newPtr = (struct Node*)malloc(sizeof(Node));newPtr->data = i;newPtr->next = NULL;cur->next = newPtr; cur = cur->next;}}cur->next = NULL;return head;}void printNode(struct Node * head){cout<<"print node"<<endl;struct Node * lptr = head;while (lptr){cout<<lptr->data<<endl;lptr = lptr->next;}}void destroyList(struct Node * head){cout<<"destroy list"<<endl;struct Node *cur = head;int i = 0;while (head){cur = head;cout<<cur->data<<endl;head = head->next;free(cur);}}Node* reverseList(struct Node * head){Node *prior = head;Node * cur = prior->next;Node * next = NULL;while (cur->next)//prior->cur->next{next = cur->next;cur->next = prior;//prior<-cur->nextprior = cur; // prior cur ;move to the next node for next loopcur = next;}head->next = NULL; //set the tail as NULLcur->next = prior; //the last loop , since the cur->next is null , //the pointer is still from head to cur,so we must reverse it additionalprintNode(cur);return cur;}void main(){struct Node *head = createList(5);printNode(head);struct Node *rhead = reverseList(head);destroyList(rhead);}
- 单链表逆序 也叫反转
- 单链表逆序反转
- 单链表反转(逆序)
- 单链表逆序/反转
- 单链表反转/逆序
- 逆序反转单链表 Python 版
- 【链表】逆序输出单链表(单链表反转)
- 单链表反转/逆序的两种方法
- 单链表反转/逆序的两种方法
- 单链表反转/逆序的两种方法
- 单链表反转/逆序的两种方法
- 什么叫控制反转?
- 荷包蛋也叫鸡蛋
- IO逆序反转输出
- 反转问题(逆序)
- 什么叫控制反转IoC
- 单链表反转/逆序的三种方法(整理)
- 单链表的反转/逆序的三种方法
- 无法转化为项目财富的技术或功能就是"垃圾"
- 经验从哪里来?从痛苦中来!
- 关于面试中经常出现的根据一个随机数构造另外的随机数的解法
- 启程
- hdu 1496 hash 方程解的情况
- 单链表逆序 也叫反转
- Linux锐捷上网
- 向Google学习打造灵动的web体验
- 大话软件开发与开车的共同点
- OpenCV:CvMemStorage
- Android开发Java图书推荐
- 软件测试工具
- IT人的好习惯和不良习惯总结
- 用C#检查一个进程是否打开