做链表的时候尝试实现三个方法,一个删除链表,一个插入数据(比如链表数据是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: 递归反输出链表值(使用头插法)无法运行。。