gpt4 book ai didi

c - 在C中打印双向链表的下一个和上一个值

转载 作者:行者123 更新时间:2023-11-30 19:22:41 27 4
gpt4 key购买 nike

我正在c中创建一个双向链表。我想打印出我的上一个和下一个值来检查我的双向链表是否正确。

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

void add(int number);
void print();
void add_to(int number);
void append(int number);
void main(){

int i = 1;

add(1);
add(2);
add(3);
print();


}
void add_to(int number){
struct node *head;
head=LINK;
head = (struct node *)malloc(sizeof(struct node));
head->d = number;
head->prev = NULL;
head->next = NULL;

if(LINK == NULL)
{
LINK = head;
head -> next = NULL;
head -> prev = NULL;
}else{
//head -> next = LINK;
//head -> prev = LINK;
//LINK = head;
}


}
//add other values
void append(int number){
struct node *kop, *right;

printf("add_new_value\n");
kop = (struct node *)malloc(sizeof(struct node));
kop -> d = number;
right = LINK;

while(right->next != NULL)
right=right->next;

right->next =kop;
right=kop;
right->next=NULL;
right->prev=NULL;


}
//add first value
void add(int number){
struct node *head;

head=LINK;
if(head==NULL){
printf("List is leeg!\n");
add_to(number);
}else{
printf("List bevat item\n");
append(number);
}
}

void print(){
printf("----------------------PRINT--------------------------\n");
struct node *n;
int *p;

while(n!=NULL){
//next_value = n->next;
printf("%d",n->d);


//printf("%d",n->next);
//printf("%d",n->next);
//printf("||\n ");
n = n->next;
}
}

.h 文件

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

typedef int DATA;
struct node{
DATA d;
struct node *prev;
struct node *next;
} *LINK;

最佳答案

void printNode(struct *node){
if (node) {
int pp = node->prev ? node->prev->d : -1;
int nn = node->next ? node->next->d : -1;
printf("[p:%d] [c:%d] [n:%d]", pp, node->d, nn);
} else {
printf("(null)");
}
}

void print(struct node *head){
printf("----------------------PRINT--------------------------\n");
struct node *n = head;
while(n!=NULL){
printNode(n);
}
}

关于c - 在C中打印双向链表的下一个和上一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15466601/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com