数据结构链表反转算法
链表是数据结构中非常重要的一种结构,今天小编就在这分享一段“反转链表的源码”
**#include<stdio.h>
#include<malloc.h>
void createHeadNode();
void createNewNode(struct node *phead);
void showList(struct node *phead);
void showRevwesalList(struct node *phead2);
void findLastNode(struct node *phead);
void reversalList(struct node *phead);
struct node{
int num;
struct node *pnext;
};
struct node *phead = NULL;
struct node *phead2 = NULL;
int main(){
int n = 0;
createHeadNode();
createNewNode(phead);
findLastNode(phead);
while (n < 5){
reversalList(phead);
n++;
}
showRevwesalList(phead2);
return 0;
}
void createHeadNode(){
phead = (struct node*)malloc(sizeof(struct node));
phead->pnext = NULL;
}
void createNewNode(struct node *phead){
struct node *top = phead;
struct node *pnew = NULL;
for (int i = 0; i < 5; i++){
pnew = (struct node*)malloc(sizeof(struct node));
if (i == 0){
pnew->num = 1;
}
else if (i == 1){
pnew->num = 2;
}
else if (i == 2){
pnew->num = 3;
}
else if (i == 3){
pnew->num = 4;
}
else if (i == 4){
pnew->num = 5;
}
pnew->pnext = NULL;
top->pnext = pnew;
top = top->pnext;
}
showList(phead);
}
void showList(struct node *phead){
struct node *top1 = phead->pnext;
printf("反转前:\n");
while (top1 != NULL){
printf("%d ", top1->num);
top1 = top1->pnext;
}
}
void findLastNode(struct node *phead){
phead2 = phead->pnext;
while (phead2 ->pnext!= NULL){
phead2 = phead2->pnext;
}
}
void showRevwesalList(struct node *phead2){
printf("\n反转后:\n");
while (phead2 != phead){
printf("%d ", phead2->num);
phead2 = phead2->pnext;
}
}
void reversalList(struct node *phead){
struct node *top2 = phead;
struct node *top3 = phead->pnext;
while (top3->pnext!= NULL){
top3 = top3->pnext;
top2 = top2->pnext;
}
top2->pnext = NULL;
top3->pnext = top2;**
}
希望这段源码能够帮助正在学习链表的老铁们!!!!