链表插入节点(C)

编写下列函数:

(1)create(n):创建并返回链表,链表包含n个节点,每个节点存储一个整数;n个整数由控制台按升序输入。函数返回创建的链表

(2)find(head,num):从链表中查找整数v,若存在,则删除num节点并返回链表;若num不存在,则将num插入到链表中,仍保持链表中节点的整数值按升序排序。

(3)print(head)

输入样例1:

(1)第1行输入n

(2)第2行按升序输入n个整数,空格隔开

(3)第3行输入要查找(或插入)的整数

10
1 3 5 7 9 11 13 15 17 19
7

输出样例1:

1 3 5 9 11 13 15 17 19 

输入样例2:

10
1 3 5 7 9 11 13 15 17 19
10

输出样例2:

1 3 5 7 9 10 11 13 15 17 19 
#include<stdio.h>
#include<stdlib.h>


//定义一个结构体
struct node
{
    int data;
    struct node *next;
};

struct node *create(int n)
{
    int i;
    struct node *head, *pnew, *ptail;
    pnew = (struct node*)malloc(sizeof(struct node));
    scanf("%d",&pnew->data);
    head = ptail = pnew;
    for(i = 1; i < n;i++)
    {
        pnew = (struct node*)malloc(sizeof(struct node));
        scanf("%d",&pnew->data);
        ptail -> next = pnew;
        ptail = pnew;
    }//for
    ptail->next = NULL;
    return head;

}//create

struct node *find(struct node *head,int num)
{
    struct node *p,*pnew,*pold;
    //对头节点进行处理
    p = head;
    pnew = (struct node *)malloc(sizeof(struct node));//创建新节点
    pnew -> data = num;//将信息储存在新的节点里
    if(head -> data > num)//如果第一个数大于num则插入在头节点前面
    {
        pnew -> next = head;
        head = pnew;
        return head;
    }//if
    if(head -> data == num)//如果第一个数等于num则删除
    {
        head = head -> next;
        free(p);//释放p
        p = head;//重新指向新的head
        return head;
    }//if

    //对之后的节点进行处理

    while(p -> next != NULL)
    {
        pold = p;
        p = p -> next;
        if(p -> data == num)//相等则删
        {
            pold -> next = p -> next;
            free(p);//释放后p为NULL
            p = pold -> next; //将释放后的p链接到pold上
            break;
        }//if

        if(p -> data > num)//大于则插入
        {
            pnew -> next = p;//将后面链接到新的节点
            pold -> next = pnew; //将处理后的链表与前面的链表进行链接
            break;
        }//if
    }//while

    if(p -> next == NULL)//如果遍历后没有执行以上代码则将新的节点接在整个链表的后面
    {
        p -> next = pnew;
        pnew -> next = NULL;
    }//if

    return head;
}//find

void print(struct node *head)//输出链表信息
{
    struct node *p=head;
    while(p!=NULL)
    {
        printf("%d ",p->data);
        p = p->next;
    }//while
}

int main()
{
    int n,num;
    struct node *head;
    printf("请输入链表节点个数:\n");
    scanf("%d",&n);
    printf("请输入各节点的值(按升序排序):\n");
    head=create(n);//创建链表
    printf("请输入要查找的数字:\n");
    scanf("%d",&num);
    head=find(head,num);//调用函数返回查找后的链表
    print(head);//输出最后的链表信息
    return 0;
}

 


版权声明:本文为yun_oyun原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。