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

标签 c list printing

我正在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/

相关文章:

C memcpy 到结构分配

检查字符串是否可以在 C 中改变

angularjs - 使用 ui-sref-active 更改 li 的背景和颜色

java - 查找未排序集合的不同元素的最大值/最小值

ios - 拖放以在列表 SwiftUI 中移动行

java - System.out.println() 中的 toString() 方法两次调用?

internet-explorer - IE 上的 iframe.print 与 window.print - 以前的小字体

c - 将整数指针设置为整数数组并将参数传递给 pthread_create

javascript - 我可以在电子邮件通讯中使用“单击打印”按钮吗?

c - 顶点属性除数不适用于实例渲染