单链表的逆序输出
部分参考
http://blog.csdn.net/niuer09/article/details/5961004
要求将一带链表头List head的单向链表逆序。
分析:
1). 若链表为空或只有一个元素,则直接返回;
2). 设置两个前后相邻的指针p,q. 将p所指向的节点作为q指向节点的后继;
3). 重复2),直到q为空
4). 调整链表头和链表尾
示例:以逆序A->B->C->D为例,图示如下
#include "stdafx.h" #include <iostream> using namespace std; struct node{ int data; struct node * next; }; typedef struct node* List; int _tmain(int argc, _TCHAR* argv[]) { const int len=10; List head=new node; List p=head; head->data=0; for(int i=0;i<len;++i) { List q=new node; q->data=rand()%10; p->next=q; p=q; } p->next=NULL; p=head; cout<<"逆序排列前"<<endl; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<endl<<"逆序排列后"<<endl; p=head; List q=p->next; List t=NULL; while(q!=NULL) { t=q->next; q->next=p; p=q; q=t; } head->next=NULL; head=p; p=head; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } return 0; }