创建双向循环链表(C语言)——尾插法

创建结构体

#include
#include
typedef int ElemType;
typedef struct node{
    struct node *prev;
    ElemType data;
    struct node *next;
}NODE;

创建头结点

NODE* CreateNode(){
    NODE *head=(NODE*)malloc(sizeof(NODE));
    head->data=-1;
    head->prev=head;
    head->next=head;
    return head;
}

插入结点

void InsertNode(NODE *head,int data){
    NODE *NewNode=(NODE*)malloc(sizeof(NODE));
    NewNode->data=data;
    NewNode->prev=head->prev;//新插入的结点的prev只需返回前驱
    NewNode->next=head;//新插入的结点的next需要返回head
    head->prev->next=NewNode;
    head->prev=NewNode;
}

遍历

void Traverse(NODE *head){
    NODE *p=head->next;
    while(p!=head){
        printf("%d ",p->data);
        p=p->next;
    }
}

主函数

int main(){
    NODE *head=CreateNode();
    int i,length;
    int data;
    scanf("%d",&length);
    for(i=0;i

完整代码

#include
#include
typedef int ElemType;
typedef struct node{
    struct node *prev;
    ElemType data;
    struct node *next;
}NODE;

NODE* CreateNode(){
    NODE *head=(NODE*)malloc(sizeof(NODE));
    head->data=-1;
    head->prev=head;
    head->next=head;
    return head;
}

//在链表尾部插入结点,建议用2+个结点举例写,更加具有普遍性
void InsertNode(NODE *head,int data){
    NODE *NewNode=(NODE*)malloc(sizeof(NODE));
    NewNode->data=data;
    NewNode->prev=head->prev;//新插入的结点的prev只需返回前驱
    NewNode->next=head;//新插入的结点的next需要返回head
    head->prev->next=NewNode;
    head->prev=NewNode;
}

void Traverse(NODE *head){
    NODE *p=head->next;
    while(p!=head){
        printf("%d ",p->data);
        p=p->next;
    }
}

int main(){
    NODE *head=CreateNode();
    int i,length;
    int data;
    scanf("%d",&length);
    for(i=0;i

你可能感兴趣的:(链表,c语言,数据结构)