我必须处理链表,甚至在main中发生某些事情之前,我就会遇到一个严重的访问错误。我不知道怎么了。我对动态内存管理比较陌生。如果有人能看一下功能就好了。申报单是由教授出具的,所以我们必须退回一张DoubleNote*。我的代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
double var;
struct node *next;
} DoubleNode;
DoubleNode* insertFirst(DoubleNode* head, double d){
DoubleNode* new_head;
new_head = (DoubleNode*)malloc(sizeof(DoubleNode));
if (new_head == NULL) {
printf("Error: Allocating memory for new node failed!");
exit(1);
}
new_head->var = d;
new_head->next = head;
head = new_head;
return head;
}
DoubleNode* inserLast(DoubleNode* head, double d){
DoubleNode* current = head;
while (current != NULL) {
current = current->next;
}
current->next = (DoubleNode*)malloc(sizeof(DoubleNode));
if (current->next == NULL) {
printf("Error: Allocating memory for new node failed!");
exit(1);
}
current->next->var = d;
current->next->next = NULL;
return head;
}
DoubleNode* inverseDoubleListCon(DoubleNode* head){
DoubleNode* current = head; // iteration variable starts on head of old list
DoubleNode* conHead = current; // Head of the new list
while (current != NULL) {
current = current->next; //iteration step
DoubleNode* newConHead = (DoubleNode*)malloc(sizeof(DoubleNode)); //allocating memory for new head
if (newConHead == NULL) {
printf("Error: Allocating memory for new node failed!");
exit(1);
}
newConHead = current; // new_head is the next variable in the old list
newConHead->next = conHead; //new head points to old head of the new list
conHead = newConHead; // new head is set
}
return conHead;
}
void printList(DoubleNode* head){
DoubleNode* current = head;
while (current != NULL) {
printf("%lfn", current->var);
current = current->next;
}
}
int main(){
DoubleNode* head = NULL;
DoubleNode* inverseHead = NULL;
double d;
int i;
int sizeOfList;
printf("Insert amount of variables: n");
scanf("%d", &sizeOfList);
for (i = 0; i < sizeOfList; i++) {
printf("Insert variable for node [%d]: n", i);
scanf("%lf", &d);
head = insertFirst(head, d);
}
printList(head);
inverseHead = inverseDoubleListCon(head);
printList(inverseHead);
return 0;
}
首先未初始化sizeOfList
。您需要添加代码来从用户那里获取大小的值。
您也不会从insertFirst
函数更新头指针的值。下面的代码应该会有所帮助。
DoubleNode* head= NULL;
// Code to get the value of sizeofList
for (i = 0; i < sizeOfList; i++)
{
...
head = insertFirst(head, d);
}
反向函数过于复杂。您正在newConHead
中分配内存,这对于反转链表是不需要的。
我建议按照"如何仅使用两个指针反转单链表?或http://www.geeksforgeeks.org/write-a-function-to-reverse-the-nodes-of-a-linked-list/