c语言链表结点的插入
生活随笔
收集整理的這篇文章主要介紹了
c语言链表结点的插入
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include<stdio.h>
struct student { //建立結構體變量struct studentlong num;float score;struct student *next
};
int n;
struct student *insert(struct student *head, struct student *stud) //函數的參數是head和stud,head是為了指向表頭,//stud目的是將待插入結點的地址從實參傳給stud
{struct student *p1;struct student *p2;struct student *p0; //定義三個結構體變量,其中p0為帶插入點的地址p1 = head;p0 = stud;if(head==NULL){ //原鏈表為空,即原來無結點,只需讓head直接等于p0head = p0; //并且讓p0的next指向空地址,即只含一個結點p0->next = NULL;}else { //若鏈表不為空,則分為兩種情況while ((p0->num > p1->num) && p1->next != NULL) //其中一種情況是插入的結點既不在第一個,也不在最后一個,即插入的點在中間{ //讓p2等于p1,且讓p1指向下一個結點p2 = p1; //一直找到p0小于等于p1為止,即p0需在p1的前面p1 = p1->next;}if (p0->num <= p1->num) { //當結點p1前面的情況if(p1==head) { //判斷p1是否是表頭,即判斷p0是否要插在第一個表頭的位置head == p0; //若是,直接讓head=p0p0->next = p1;}else { //p1不是表頭,則一定做了while循環,就會有p2的值p2->next = p0; //則讓p0插在p2和p1之間p0->next = p1;}}else { //插入的結點在表尾的情況p1->next = p0; //則讓p1的next指向p0,p0后面沒有結點了,即next指向空地址p0->next = NULL;}n = n + 1; //結點數加1return(head);}
}
總結
以上是生活随笔為你收集整理的c语言链表结点的插入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 评测3款高颜值的azw3阅读器(ios手
- 下一篇: java过滤器全局解析token