#include <stdio.h>
#include<stdlib.h>
typedef struct student {
int num;
struct student* pnext;
}stu, * pstu;
void list_print(pstu phead)
{
while (phead)
{
printf("%d ", phead->num);
phead = phead->pnext;
}
}
void list_tail_insert(pstu* pphead, stu** pptail, int i) { //尾插法
pstu pnew = (pstu)calloc(1, sizeof(stu)); //申请结构体节点的空间,calloc不用初始化节点pnext
pnew->num = i;
if (*pphead == NULL) { *pphead = pnew; *pptail = pnew; } //链表为空,头尾指针都指向新节点
else { (*pptail)->pnext = pnew; *pptail = pnew; } //原本尾节点的*pnext指向新节点,新节点作为尾节点
}
pstu invertlist(pstu head) //逆转链表,其实是头插法新建链表
{
if (head == NULL)
{
printf("List is empty");
return NULL;
}
pstu phead = (pstu)calloc(1, sizeof(stu)); //建立头节点
phead->num = head->num;
head = head->pnext;
while (head) //不止一个节点继续遍历原链表
{
pstu pnew = (pstu)calloc(1, sizeof(stu)); //建立新节点pnew指向phead
pnew->pnext = phead;
pnew->num = head->num; //赋值新节点
head = head->pnext; // 原链表后移
phead = pnew; //头指针指向新节点
}
return phead;
}
int main() {
pstu phead1, ptail1;
phead1 = ptail1 = NULL;
int i;
printf("list:");
while (scanf_s("%d", &i) != EOF)
{
list_tail_insert(&phead1, &ptail1, i);
}
printf("\ninvertlist:");
list_print(invertlist(phead1));
return 0;
}
进阶:
求链表的倒数第n个节点
#include <stdio.h>
#include<stdlib.h>
typedef struct student {
int num;
struct student* pnext;
}stu, * pstu;
void list_print(pstu phead)
{
while (phead)
{
printf("%d ", phead->num);
phead = phead->pnext;
}
}
void list_tail_insert(pstu* pphead, stu** pptail, int i) { //尾插法
pstu pnew = (pstu)calloc(1, sizeof(stu)); //申请结构体节点的空间,calloc不用初始化节点pnext
pnew->num = i;
if (*pphead == NULL) { *pphead = pnew; *pptail = pnew; } //链表为空,头尾指针都指向新节点
else { (*pptail)->pnext = pnew; *pptail = pnew; } //原本尾节点的*pnext指向新节点,新节点作为尾节点
}
pstu invertlist(pstu head)
{
if (head == NULL)
{
printf("List is empty");
return NULL;
}
pstu phead = (pstu)calloc(1, sizeof(stu)); //建立头节点
phead->num = head->num;
head = head->pnext;
while (head) //不止一个节点继续遍历原链表
{
pstu pnew = (pstu)calloc(1, sizeof(stu)); //建立新节点pnew指向phead
pnew->pnext =phead;
pnew->num = head->num; //赋值新节点
head = head->pnext; // 原链表后移
phead = pnew; //头指针指向新节点
}
return phead;
}
int main() {
pstu phead1, phead2, ptail1, ptail2;
phead1 = ptail1 = NULL;
phead2 = ptail2 = NULL;
int i,m,cnt=0;
printf("list:");
while (scanf_s("%d", &i) != EOF)
{
list_tail_insert(&phead1, &ptail1, i);
cnt++;
}
list_print(phead1);
printf("\ninvertlist:");
list_print(invertlist(phead1));
printf("\n倒数第几个节点:");
scanf_s("%d", &m);
if(m>cnt) printf("超过链表个数");
else {
printf("\nThe %d to last node is:", m);
phead2 = invertlist(phead1);
for (int j = 1; j < m; j++)
{
phead2 = phead2->pnext;
}
printf("%d", phead2->num);
}
return 0;
}