首页 > 其他 > 详细

无头结点链表

时间:2020-03-26 23:10:51      阅读:72      评论:0      收藏:0      [点我收藏+]
# 温凯老师数据结构

```c
#include <stdio.h>
#include <stdlib.h>

typedef struct _node
{
    int data;
    struct _node *next;
}Node;

typedef struct _list
{
    Node *head;
}List;
void InsertList(List *list,int num);
void AddListByEnd(List *list,int num);
void AddListByHead(List *list,int num);
void Print(List *list);
void Free(List *list);
int main(void)
{
    List list;
    list.head=NULL;
    int num;
    do
    {
        printf("请输入一个数字:");
        scanf("%d",&num);
        if(num!=-1)
        {
            AddListByEnd(&list,num);
        }
    } while (num != -1);
    Print(&list);
    printf("请输入你要删除的数字:");
    scanf("%d",&num);
    Node *p,*q;
    for(q=NULL,p=list.head;p;q=p,p=p->next)
    {
        if(p->data==num)
        {
            if(q)
            {
                q->next=p->next;
            }
            else
            {
                list.head=p->next;
            }
            
        }
    }
    Print(&list);
    InsertList(&list,5);
    Print(&list);

    system("pause");
    return 0;    
}

void AddListByHead(List *list,int num)
{
    Node *p;
    p=(Node *)malloc(sizeof(Node));
    p->data=num;
    

    if(list->head)
    {
        p->next=list->head;
        list->head=p;
    }
    else
    {
        list->head=p;
        p->next=NULL;
    }
    
}

void Print(List *list)
{
    Node *p;
    for(p=list->head;p;p=p->next)
    {
        printf("%d\n",p->data);
    }
    printf("\n");
}

void Free(List *list)
{
    Node *p,*q;
    for(p=list->head;p;p=q)
    {
        q=p->next;
        free(p);
    }
}

void AddListByEnd(List *list,int num)
{
    Node *p;
    p=(Node *)malloc(sizeof(Node));
    p->data=num;
    static Node *tail;

    if(list->head)
    {
        tail->next=p;
        p->next=NULL;
    }
    else
    {
        list->head=p;
        p->next=NULL;
    }
    tail=p;
    
}

void InsertList(List *list,int num)
{
    Node *current,*previous,*new;
    current=list->head;
    previous=NULL;

    while(current != NULL && current->data <num)
    {
        previous=current;
        current=current->next;
    }

    new=(Node *)malloc(sizeof(Node));

    new->data=num;
    new->next=current;

    if(previous)
    {
        previous->next=new;
    }
    else
    {
        list->head=new;
    }
    


}
```

 

无头结点链表

原文:https://www.cnblogs.com/Knightl8/p/12577781.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!