title: reverse the linkList
date: 2020-09-23 17:49:03
tags: [链表头插, 链表逆置, C语言, 算法, AL, DS]
categories: DSandAL
#include <stdio.h>
#include <stdlib.h>
typedef struct MyStruct
{
int data;
struct MyStruct* next;
}Node, *pList;
void Reverse(pList *);
void Print(pList);
void ReverseOrder(pList*);
int main(void)
{
pList pHead = NULL;
Reverse(&pHead);
printf("对空链表头插5个结点:\n");
Print(pHead);
printf("头插完之后,将链表元素转置:\n");
ReverseOrder(&pHead);
Print(pHead);
return 0;
}
void Reverse(pList * ppHead)
{
int i;
pList pNewNode;
for(i = 1; i < 6; i++)
{
pNewNode = (pList) malloc(sizeof(Node));
pNewNode->data = i;
pNewNode ->next = *ppHead;
*ppHead = pNewNode;
}
}
void Print(pList phead)
{
pList temp = phead;
while(temp != NULL)
{
printf("%d\n", temp->data);
temp = temp -> next;
}
}
void ReverseOrder(pList* pphead)
{
pList p = *pphead, q = (*pphead) ->next;
*pphead = NULL;
while(q != NULL)
{
p -> next = *pphead;
*pphead = p;
p = q;
q = q->next;
}
p->next = *pphead;
*pphead = p;
}