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

时间:2013-03-17 21:45:08

标签: c list printing

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

#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;

1 个答案:

答案 0 :(得分:1)

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);
    }
}