.T21 2021-04-05 12:01 采纳率: 50%
浏览 64

C语言链表头插法问题+递归反向输出

做链表的时候尝试实现三个方法,一个删除链表,一个插入数据(比如链表数据是1,2,3,4插入index为0的数据8会使链表变成8,1,2,3,4),一个递归反向输出链表

#include <stdio.h>
#include "string.h"
#include "stdlib.h"

typedef struct node {
    int data;
    struct node* next;
}Node;

int main() {
    struct node *newn = malloc(sizeof(struct node));
    struct node *newn2 = malloc(sizeof(struct node));
    newn->next = NULL;
    Push(&newn, 1);
    Push(&newn, 2);
    Push(&newn, 3);
    Push(&newn, 4);

    
    /*
    DeleteList(newn);//?
    printQueue(newn);*/
    

    InsertNth(&newn,0,1);//?插入idex为0位置的时候会输出一个内存?
    InsertNth(&newn,1,2);
    InsertNth(&newn,3,8);
    printQueue(newn);

    /*
    RecursiveReverse(&newn);//?
    printQueue(newn);*/

    return 0;

}


void Push(Node**headRef, int newData){


    Node *head = *headRef;
    struct node *newn = malloc(sizeof(struct node)); //
    newn->data = newData;
    newn->next = head;
    head = newn;

    *headRef = head;

}

int Pop(Node* head){
    struct node *newn = malloc(sizeof(struct node));
    if(head->next == NULL){
        return 0;
    }
    newn->next = head->next;
    head->next = NULL;
    return head->data;
}

void DeleteList(Node**head){
    struct node* headnew= *head;
    while(headnew->next != NULL){
        DeleteList(&(headnew->next));
    }
    free(headnew);
    *head = NULL;//?
}

void InsertNth(Node**head, int index, int data){
    Node *headnew = *head;
    struct node *newn = malloc(sizeof(struct node));
    newn->data = data;
    if(index == 0){
        //check if start
        Push(*head,data);
        return;
    }
    index--;
    while (headnew != NULL && index != 0){
        headnew = headnew->next;
        index--;
    }
    if(index != 0){
        return;

    }
    newn->data = data;
    newn->next = headnew->next;
    headnew->next = newn;

}

void RecursiveReverse(Node**headRef){
    Node* head = *headRef;
    Node* newn;
    newn = head;
    if(newn->next !=NULL){
        RecursiveReverse(&(newn->next));
    }
    Node* newn2 = newn;
    while(newn->next != NULL){
        newn = newn->next;
    }
    head->next =NULL;
    newn->next = head;
    *headRef= newn2;    
}

void printQueue(Node* l){
    while(l->next != NULL){//
        printf("data is %d\n", l->data);
        l = l->next;
    }
    printf("\n");
}

问题1:不确定delete方法是否删除了所有的链表并且free了内存,因为输出是-1073741819 (0xC0000005),如果没有删除链表,请问该如何具体实现delete方法。

问题2: insert方法在输入index为0的时候结尾会输出一个内存地址。

问题3: 递归反输出链表值(使用头插法)无法运行。。

  • 写回答

2条回答 默认 最新

  • 关注

    没看到push 函数呢,看看是不是问题在里面

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?