头插法和尾插法实现链表逆序
时间:2022-05-27 22:35:56
收藏:0
阅读:12
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node* next;
}Node,*List;
void ReverseList(List L)
{
Node* node1;
Node* node2;
List L2=(List)malloc(sizeof(Node));
L2->next=NULL;
node1=L->next;
while(node1)
{
node2=(Node*)malloc(sizeof(Node));
node2->data=node1->data;
node2->next=L2->next;
L2->next=node2;
node1=node1->next;
}
Node* node;
node=L2->next;
while(node)
{
printf("%d ",node->data);
node=node->next;
}
}
void CreateList(List L, int k)
{
Node *node,*rear=L;
//尾插法创建节点
for(int i=0;i<k;i++)
{
node=(Node*)malloc(sizeof(Node));
scanf("%d",&node->data);
rear->next=node;
rear=node;
}
rear->next=NULL;
}
void Print(List L)
{
Node* node;
node=L->next;
while(node!=NULL)
{
printf("%d ",node->data);
node=node->next;
}
printf("\n");
}
int main()
{
List L=(List)malloc(sizeof(Node));
L->next=NULL;
CreateList(L,5);
Print(L);
ReverseList(L);
return 0;
}
原文:https://www.cnblogs.com/iGhost/p/15350463.html
评论(0)