C++经典算法————链表倒序

来源:互联网 发布:thinkpad t470p 知乎 编辑:程序博客网 时间:2024/05/18 00:16
这学期去就是大四了,马上要面临各种招聘,面试,这里把一些经典算法,回顾下。

链表的倒序,写的不怎么好,但基本思路是这样的

// testforList.cpp : 定义控制台应用程序的入口点。////链表倒序,算法实现#include "stdafx.h"#include "windows.h"#include "iostream"using namespace std;struct Node{int data;Node * next;};int _tmain(int argc, _TCHAR* argv[]){Node * head;//链表的头部head=(Node *)malloc(sizeof(Node));head->data=-1;head->next=NULL;//链表的生成,p在q的前面,p的next就是qNode * p,* q;p=head;for (int i = 0; i < 10; i++){q=(Node*)malloc(sizeof(Node));q->data=i;p->next=q;p=q;}//循环结束后,最后一个节点为p,所以p的nest为nullp->next=NULL;//开始链表倒序,把head付给p,head的next付给q,然后把head的next为空p=head;q=head->next;head->next=NULL;Node * t;//临时变量t=(Node*)malloc(sizeof(Node));t=NULL;while (q){t=q->next;//临时变量存储q后面的地址,相当于p存第一个数据地址,q存第二个数据地址,t存第三个数据地址q->next=p;//第二个数据地址q的next存第一个数据地址,这样就完成了倒序p=q;//然后第二个数据地址换成p,第三个数据地址换成q,t在第二轮循环编程第四个数据q=t;}//倒序输出do {cout<<p->data<<endl;p=p->next;} while (p);system("pause");return 0;}


0 0
原创粉丝点击