需要为初学者提供链接列表基本建议

时间:2015-09-06 03:07:24

标签: c struct linked-list

老师说写程序有四个功能(打印大小或添加,删除和打印节点)。第17行出现错误(无法将int *转换为节点)。我找不到其他方式来代表这条线,所以请帮忙。由于这是我第一次使用链表,您可能会遇到大量错误。

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
struct node{                // Declaring the node (2 way)
    int n;
    struct node *next;
    struct node *prev;
};
int *header;                //Declaring header and size counter
int size;

int *finder(int number)     //Function that return address of selected node       
{
    int *adr;
    int c;
    struct node *temp;
    temp=header;
    c=0;
    while(c==number)
    {
         temp=temp->next;
         c=c+1;
    }
return adr;
}

void insert(int data,int number)    //insert new node after specified node
{
    int *adr;
    adr=finder(number);
    struct node *current;
    struct node *previous;
    struct node *temp;

    temp=(struct node *)malloc(sizeof(struct node));
    current=adr;
    previous=current->prev;

    temp->n=data;
    temp->next=current;
    temp->prev=current->prev;

    previous->next=temp;
    current->prev=temp;

    size=size+1;
}

void remove(int number)             //remove node after selected one
{
    int *adr;
    adr=finder(number);
    struct node *current;
    struct node *previous;
    struct node *neeext;
    current=adr;
    previous= current->prev;
    neeext= current->next;

    previous->next= neeext;
    neeext->prev= previous;
}

void print(int number)          //print data of node
{
    int *adr;
    adr=finder(number);
    struct node *current;
    printf("%d",current->n);
}

int main()                          //main function
{
    int i,j,d;
    size=0;
    for(i=1;i<5;i=i+0)
    {
        if(i==1)
        {
            printf("%d",size);  
        }
        scanf("%d",&j);
        if(i==2)
        {
            scanf("%d",&d);
            insert(d,j);
            printf("inserted");
        }
        if(i==3)
        {
            remove(j);
            printf("removed");
        }
        if(i==4)
        {
            print(j);
        }
        if(i==5)
        {
            return 0;
        }
        scanf("%d",&i);
        printf("\n");
    }
}

1 个答案:

答案 0 :(得分:3)

您应将header变量声明为struct node *header;,而不是int*