本文主要是介绍单链表倒序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include<stdio.h>
#include<stdlib.h>
#include <malloc.h>
/*链表的定义,从头添加数据,从尾添加数据,打印链表,将链表倒序*/
struct student//结构体
{
int id;
char nName[20];
float sc;
};
typedef student DATA;//结构体的别名
struct SNode//单链表
{
DATA data;
SNode *pNext;
};
SNode *g_pHead=NULL;//头指针
int Add_List(DATA data)//从头添加数据
{
SNode *p = (SNode *)malloc(sizeof(SNode));//申请空间
p->data = data;
p->pNext = g_pHead;
g_pHead = p;
return 0;
}
int Add_List_p(DATA data)//从尾添加数据
{
SNode *p1 = (SNode *)malloc(sizeof(SNode));
p1->data = data;
p1->pNext = NULL;//尾部NULL
if (g_pHead == NULL)
{
g_pHead = p1;
}
SNode *p = g_pHead;
while (p ->pNext!= NULL)//遍历到尾部
{
p = p->pNext;
}
p->pNext = p1;
return 0;
}
int Prt_List()//打印链表
{
SNode *p = g_pHead;//保护头指针
while (p!=NULL)
{
printf("%d\t", p->data.id);
printf("%s\t", p->data.nName);
printf("%0.1f\t\n", p->data.sc);
p = p->pNext;
}
return 0;
}
SNode * re_List(SNode *L)//倒序
{
SNode *current, *pnext, *prev;
if (L == NULL || L->pNext == NULL)
return L;
current = L->pNext; // p1指向链表头节点的下一个节点
pnext = current->pNext;
current->pNext = NULL;
while (pnext)
{
prev = pnext->pNext;
pnext->pNext = current;
current = pnext;
pnext = prev;
}
//printf("current = %d,next = %d \n",current->data,current->next->data);
L->pNext = current; // 将链表头节点指向p1 //
return L;
}
/*SNode *p1 = g_pHead->pNext;
SNode *p2 = p1->pNext;
SNode *p3 = p2->pNext;
p1->pNext = NULL;
while (p1->pNext!=NULL)
{
p2->pNext=p1;
p1 = p2;
p2 = p3;
}
g_pHead->pNext = p1;
return g_pHead;
*/
int main()
{
Add_List({ 3,"sb", 30 });
Add_List({ 2 ,"eb", 360 });
Add_List({ 1 ,"sbe", 50 });
Add_List_p({ 4 ,"sb", 30 });
Add_List_p({ 5 ,"eb", 360 });
Add_List_p({ 6 ,"sbe", 50 });
Prt_List();
g_pHead = re_List(g_pHead);
Prt_List();
return 0;
}
这篇关于单链表倒序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!