1. 程式人生 > 其它 >頭插法和尾插法實現連結串列逆序

頭插法和尾插法實現連結串列逆序

#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;
}