以下結點node定義了一個學生的信息。函數find查找並返回學號小於num,且下一節點學號不小於num的結點指針

  • 以下結點node定義了一個學生的信息。函數find查找並返回學號小於num,且下一節點學號不小於num的結點指針。函數insert按學號遞增順序插入新學生。測試主函數從鍵盤輸入5個學號,調用insert函數插入鏈表,並輸出鏈表內容。
  • 請補全程序,完成相應的功能。

初步實現功能

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int num;           /*學生的學號*/
    struct node *next; /*指向下一結點*/

};
struct node *find(struct node *head,int num)
{/*①如果head爲空鏈表,則返回空指針。②如果第一個結點的學號不小於num,也返回空指針。③如果最後一個結點的學號仍小於num,則返回最後一個結點指針。④如果當前結點的學號小於num且下一結點學號不小於num,則返回當前結點的指針*/
    struct node *p, *q;
    if(head==NULL || head->num>=num)
       return NULL;/*head爲空鏈表時或第一個結點的學號不小於num時返回空指針*/
    for ( p=head; p!=NULL; p=p->next )
    {
        q = p->next;
        if (q==NULL || q->num>=num)
            return p;
    }
}
struct node *insert(struct node *head,int num)
{/*按學號順序插入新結點,新結點的學號爲num*/
   struct node *p, *q;
    p = (struct node *)malloc(sizeof(struct node));/*分配內存空間*/
    p->num = num;
    q = find(head,num);/*找到插入位置在p的後面*/
    if (q==NULL)
    { /*插入到鏈表頭*/
        p->next = head;
        return p;
    }
    p->next=q->next;/*插入到q的後面*/
    q->next = p;
    return head;
}
int main()
{
    struct node *head=NULL, *p;
    int  i, num;
    for ( i=0; i<5; i++ )
    {
        scanf( "%d", &num );
        head=insert(head,num);
    }
    for ( p=head; p!=NULL; p=p->next )
        printf( "%d ", p->num );
    printf("\n");
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章