刚刚开始学习数据结构,自己尝试性地写了一个链表反转的代码,编译似乎没有问题,但运行后没有显示任何数字。
想了半天找不到原因。
请问有哪位能帮忙看看问题出在哪里吗?
十分感谢!
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* link;
};
struct Node* head = NULL;
void Print()
{
struct Node* temp = head;
while (temp != NULL)
{
printf(" %d", temp->data);
temp= temp->link;
}
printf("\n");
}
int Insert(int n)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node*));
temp = head;
while(temp->link != NULL)
{
temp = temp->link;
}
struct Node* temp2 = (struct Node*)malloc(sizeof(struct Node*));
temp2->data = n;
temp2->link = NULL;
temp->link = temp2;
if(head == NULL)
{
head = temp;
}
}
int Reverse()
{
struct Node* current, *prev , *next;
current = head;
prev = NULL;
while (current != NULL)
{
next = next->link;
current->link = prev;
prev = current;
current = next;
}
head = prev;
}
int main()
{
Insert(2);
Insert(4);
Insert(6);
Insert(8);
Print();
Reverse();
Print();
}