我需要编写一个小程序来合并2个排序的链表,不幸的是它不起作用。您应该查看imo的主要部分是Node.c文件中的mergeSortedLists,其余的应该没问题。
Node.h:
#ifndef NODE_H
#define NODE_H
#include <stdbool.h>
typedef enum {
SUCCESS=0,
MEMORY_ERROR,
EMPTY_LIST,
UNSORTED_LIST,
NULL_ARGUMENT,
} ErrorCode;
typedef struct node_t {
int x;
struct node_t *next;
} *Node;
void printList(Node list);
int getListLength(Node list);
void destroyList(Node ptr);
Node createNode(int num);
Node createNode2(int num, Node target);
bool isListSorted(Node list);
Node createNode(int x);
ErrorCode mergeSortedLists(Node list1, Node list2, Node *merged_out);
#endif
Node.c:
#include "Node.h"
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
void printList(Node list)
{
while(list){
printf(" %d", list->x);
list = list->next;
}
return;
}
int getListLength(Node list) {
int count = 0;
while (list) {
count++;
list = list->next;
}
return count;
}
bool isListSorted(Node list) {
if (list == NULL) {
return true;
}
int prev = list->x;
list = list->next;
while (list != NULL) {
if (prev > list->x) {
return false;
}
prev = list->x;
list = list->next;
}
return true;
}
void destroyList(Node ptr){
while(ptr){
Node to_delete = ptr;
ptr = ptr->next;
free(to_delete);
}
}
Node createNode(int num){
Node ptr = malloc(sizeof(*ptr));
if(!ptr){
return NULL;
}
ptr->x = num;
ptr->next = NULL;
return ptr;
}
Node createNode2(int num, Node target){
Node ptr = malloc(sizeof(*ptr));
if(!ptr){
return NULL;
}
ptr->x = num;
ptr->next = target;
return ptr;
}
ErrorCode mergeSortedLists(Node list1, Node list2, Node *merged_out)
{
if(!merged_out){
return NULL_ARGUMENT;
}
if((!list1) || (!list2)){
return EMPTY_LIST;
}
if(!(isListSorted(list1) && isListSorted(list2))){
return UNSORTED_LIST;
}
Node *tmp = merged_out;
while(list1 || list2){
if(!list1){
(*tmp)->next = createNode(list2->x);
if((*tmp)->next == NULL){
destroyList(*merged_out);
return MEMORY_ERROR;
}
tmp = &((*tmp)->next);
}
if(!list2){
(*tmp)->next = createNode(list1->x);
if((*tmp)->next == NULL){
destroyList(*merged_out);
return MEMORY_ERROR;
}
tmp = &((*tmp)->next);
}
if(list1->x < list2->x){
(*tmp)->next = createNode(list1->x);
if((*tmp)->next == NULL){
destroyList(*merged_out);
return MEMORY_ERROR;
}
tmp = &((*tmp)->next);
}
else
{
(*tmp)->next = createNode(list2->x);
if((*tmp)->next == NULL){
destroyList(*merged_out);
return MEMORY_ERROR;
}
tmp = &((*tmp)->next);
}
}
return SUCCESS;
}
主c文件:
#include <stdio.h>
#include "Node.h"
int main(){
// printf("Hello world");
Node n5 = createNode(7);
Node n3 = createNode2(5, n5);
Node n2 = createNode2(3, n3);
Node n1 = createNode2(1, n2);
Node m4 = createNode(8);
Node m3 = createNode2(7, m4);
Node m2 = createNode2(4, m3);
Node m1 = createNode2(2, m2);
Node a = createNode(1);
Node *merged = &a;
mergeSortedLists(n1, m1, merged);
printList(*merged);
printList(n1);
}
运行时出现细分错误错误,有什么想法吗?我知道我建立链表的方式比较迟钝,但是我只需要进行表面测试,因为我有另一个测试员。