【发布时间】:2021-11-13 10:07:57
【问题描述】:
我有一个简单的链接列表程序,可以创建/打印它,然后打印它的最后 2 个数字(以相反的顺序)
cat link_list.c
/**
* C program to create and traverse a Linked List
*/
#include <stdio.h>
#include <stdlib.h>
/* Structure of a node */
struct node {
int data; // Data
struct node *next; // Address
}*head;
/*
* Functions to create and display list
*/
void createList(int n);
void traverseList();
void ReverseList(struct node *);
int main()
{
int n;
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);
printf("\nData in the list \n");
traverseList();
ReverseList(head);
return 0;
}
/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;
head = (struct node *)malloc(sizeof(struct node));
// Terminate if memory not allocated
if(head == NULL)
{
printf("Unable to allocate memory.");
exit(0);
}
// Input data of node from the user
printf("Enter the data of node 1: ");
scanf("%d", &data);
head->data = data; // Link data field with data
head->next = NULL; // Link address field to NULL
// Create n - 1 nodes and add to list
temp = head;
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
/* If memory is not allocated for newNode */
if(newNode == NULL)
{
printf("Unable to allocate memory.");
break;
}
printf("Enter the data of node %d: ", i);
scanf("%d", &data);
newNode->data = data; // Link data field of newNode
newNode->next = NULL; // Make sure new node points to NULL
temp->next = newNode; // Link previous node with newNode
temp = temp->next; // Make current node as previous node
}
}
/*
* Display entire list
*/
void traverseList()
{
struct node *temp;
// Return if list is empty
if(head == NULL)
{
printf("List is empty.");
return;
}
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print data of current node
temp = temp->next; // Move to next node
}
}
static count=0, k=2;
ReverseList(struct node *head)
{
if (head == NULL)
return;
else {
ReverseList(head->next);
count++;
if (count <= k)
printf("Data = %d\n", head->data);
}
}
对于输入 1 2 3 ,它会首先正确打印 3 2 1 然后 3 2 但我对以下内容感到困惑:
if (head == NULL)
return;
用 return; 返回的究竟是什么,以及 head 在后面指向的位置
反向列表(头->下一个);声明?
【问题讨论】:
-
你的问题是什么?
-
在编写任何涉及列表或树或类似链接结构的代码之前,我建议您使用铅笔和纸来绘制所有操作。为节点绘制方框,为所有指针绘制箭头。执行操作时擦除并重新绘制箭头。在执行此操作时,记下您执行的操作的编号列表。做这一切,直到你得到一些似乎可以工作的东西,然后将编号列表转换为代码以执行操作。
-
当你开始实现算法时,一点一点地去做。将上一步(绘图和制作操作列表)中的所有点划分为更小更简单的步骤,并继续细分这些步骤,直到无法进一步划分它们。然后逐个实现每个小子步骤,在启用额外警告的情况下构建(您将其视为必须修复的错误)并进行测试。只有当它构建干净并且工作时,你才能继续下一个小步骤。
-
然后,当您的某个小块出现问题时,您可以使用调试器逐语句逐句执行相关代码,同时监控变量及其值。再次使用铅笔和纸来绘制您执行的操作,并将它们与您拥有的原始绘图和逐项(和细分)列表进行比较。如果与您在纸上的内容有任何偏差,那么这可能就是问题所在。
-
@AlexF, 但是在 ReverseList(head->next) 之后 head 为空; ,它怎么能成功打印head->data,这是我的主要疑问?
标签: c recursion reverse singly-linked-list function-definition