# c、c++中一些经典的程序总结

## 1.将一单链表逆序（完全正确版）

#include<stdio.h>
#include<malloc.h>
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*List;
void createListR(LNode *&p, int *a, int n)
{//尾插法构造单链表
LNode *s, *r;
int i;
r = p;
for (i = 0; i < n; ++i)
{
s = (LNode*)malloc(sizeof(LNode));
s->data = a[i];
r->next = s;
r = r->next;
}
r->next = NULL;
}
List reverseList(List &L)
{
List currentPos,nextPos,previousPos;
previousPos=NULL;
currentPos=L;
nextPos=L;
while(nextPos!=NULL)
{
nextPos=nextPos->next;
currentPos->next=previousPos;
previousPos=currentPos;
currentPos=nextPos;
}
currentPos=previousPos;
return currentPos;
}
void printList(LNode *p)
{//输出链表
if (p->next == NULL)
printf("链表为空！");
else
{
while (p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
}
int main()
{
int ch[10] = { 15,46,47,29,19,23,68,79,115,784 };
LNode *p,*q;
p=(LNode*)malloc(sizeof(LNode));
q=(LNode*)malloc(sizeof(LNode));
//带头节点
createListR(p,ch,10);
//printList(p->next);
q=reverseList(p->next);
printList(q);
free(q);
free(p);
return 0;
}