刚刚开始学习数据结构,自己尝试性地写了一个链表反转的代码,编译似乎没有问题,但运行后没有显示任何数字。
想了半天找不到原因。
请问有哪位能帮忙看看问题出在哪里吗?
十分感谢!
#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();
}
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *link;
};
struct Node *head = NULL;
void Print()
{
struct Node *temp = head->link; //struct Node *temp = head;
while (temp != NULL)
{
printf(" %d", temp->data);
temp = temp->link;
}
printf("\n");
}
void Insert(int n)
{
//struct Node *temp = (struct Node *)malloc(sizeof(struct Node *));
//temp = head;
// while (temp->link != NULL)
// {
// temp = temp->link;
// }
struct Node *temp;
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;
// }
}
void Reverse()
{
struct Node *current, *prev, *next;
next = current = head->link; //current = head;
prev = NULL;
while (current != NULL)
{
next = next->link;
current->link = prev;
prev = current;
current = next;
}
head->link = prev; //head = prev;
}
int main()
{
head = (struct Node *)calloc(1, sizeof(struct Node *));
Insert(2);
Insert(4);
Insert(6);
Insert(8);
Print();
Reverse();
Print();
return 0;
}
next都没有赋值,怎么能next = next->link呢
int Reverse()
{
struct Node* current, *next;
current = head;
if(current == NULL)
return 0;
next = current->link;
current->link = NULL;
while (next != NULL)
{
head = next;
head->link = current;
current = next;
next = next->link;
}
}
c语言单向链表反转6,单链表反转的问题怎么解决(C语言)_weixin_39602005的博客-CSDN博客 匿名用户1级2015-02-07 回答单链表反转:比如原链表为 head->1->2->3->NULL;反转后:head->3->2->1->NULL;实现代码:#include#includetypedefstructNode{intdata;structNode*next;}*List;#definenodestructNod... https://blog.csdn.net/weixin_39602005/article/details/117137563
和
������ת��������ô�����C���ԣ�_�ٶ�֪�� https://zhidao.baidu.com/question/1690874251714060348.html
和
C语言 单链表的反转_Genven_Liang的博客-CSDN博客_c语言反转链表 C语言 单链表的反转一、简述 记--简单的将单链表的数据顺序进行反转。如将原来的顺序1 2 3 4 5 6 7 反转为:7 6 5 4 3 2 1二、方式1:头插法 2.1 头插法1--类似新建链表 2.1.1 思路:断开链表头,然后以头插法的方式将原链表的数据添加链表。 2.1.2 测... https://blog.csdn.net/nanfeibuyi/article/details/90116419
建议看一看
如果有帮助,请采纳,谢谢