數據結構 單鏈表的插入詳解 例子

最近看了郝斌老師講的數據結構的單鏈表插入的視頻,覺得視頻中鏈表插入的算法寫的很經典,所以就把代碼敲了一下分享給大家

#include <stdio.h>  
#include <malloc.h>  
#include <time.h>
  
typedef struct list  
{  
    int vaule; //數據域  
    struct list *PNext; //指針域  
}TNODE, *TPNODE;  
  
TPNODE Creat_list();  
void Trave_list(TPNODE _PHead);  
int Insert_List(TPNODE _pHead, int _pos, int _iVal);

int main()  
{  
    int iRet = 0;
    int iVal = 0;
    int pos = 0;
    TPNODE PHead;
    srand((int)time(NULL));
    
    PHead = Creat_list();   //創建鏈表
    printf("please input insert pos\n");
    scanf("%d", &pos);
    
    printf("please input Val\n");
    scanf("%d", &iVal);
    iRet = Insert_List(PHead, pos, iVal);
    if(1 == iRet)
    {
        printf("Insert fail\n");
    }
    Trave_list(PHead);   //遍歷鏈表
  
    return 0;  
}  
  
//創建鏈表  
TPNODE Creat_list()  
{  
    int i = 0;  
    int len = 0;  
    int iVaule = 0;  
  
    TPNODE pHead;  
    pHead = (TPNODE)malloc(sizeof(TNODE));  //創建一個頭結點  
    if(NULL == pHead)   //創建失敗
    {  
        printf("create list fail\n");  
    }  
  
    TPNODE PTail = pHead;  
    pHead->PNext = NULL;  
      
    printf("please input len of list\n");  
    scanf("%d", &len);  //輸入想要的個數
    for(i = 0; i < len; i++)  
    {  
        iVaule = rand()%100+1;
  
        TPNODE pNew = (TPNODE)malloc(sizeof(TNODE)); //分配內存
          
        pNew->vaule = iVaule;  //將數據域賦予數據  
        PTail->PNext = pNew;  
        pNew->PNext = NULL;  
        PTail = pNew;  
    }  
      
    return  pHead;  
}  
      
//鏈表輸出  
void Trave_list(TPNODE _PHead)  
{  
    int i = 0;
    TPNODE P = _PHead->PNext;  
  
    while(NULL != P)  
    {  
        i = 1;
        printf("%d ", P->vaule);  
        P = P->PNext;  
    }  
    if(1 == i)
    {
        printf("\n");
    }
}  

//鏈表插入
int Insert_List(TPNODE _pHead, int _pos, int _iVal)
{
    int i = 0;
    TPNODE p = _pHead;
    while(NULL != p && i < _pos-1)
    {
        p = p->PNext;
        i++;
    }

   if(i > _pos -1 || NULL == p)
   {
        return 1; 
   }

    TPNODE pNew = (TPNODE)malloc(sizeof(TNODE));
    if(NULL == pNew)
    {
        return 1;
    }

    pNew->vaule = _iVal; //(第一行)將待插入的數據賦值到新的節點數據域中
    TPNODE q = p->PNext; //(第二行)結構體指針q指向p的下一個節點
    p->PNext = pNew; // (第三行)p的下一個節點指向新節點
    pNew->PNext = q; //此時的q爲第二行的p->pNext,不是第三行的pNew(指針思想)
    
    return 0;
}


此程序的用法:

1,首先輸入待創建鏈表的長度,輸入完畢後,程序會產生隨機數對每個節點賦值,生成鏈表

2,然後輸入待插入的位置

3,輸入待插入的數值

4,遍歷鏈表輸出

比如創建長度爲5的結點,在第三個位置插入數值爲10的數據,運行結果


插入解析,執行完插入函數中的while循環後,此時的p指針指向的是第二個結點。

然後創建一個新結點,並分配內存,然後將待插入的數值賦值到新結點的數據域中pNew->vaule = _iVal;

然後新指針q指向p->PNext,此時的p->PNext爲第三個結點。所以q的值爲第三個結點。

p->PNext = pNew; 把p->PNext指向新結點PNew,說明第三個結點爲pNew,此時PNew爲第三個結點。

pNew->PNext = q,新結點的下一個結點指向q,此時的q爲插入之前的第三個結點,執行完成後爲第四個結點。所以就完成了插入的工作。


創建鏈表的詳解:點擊打開鏈接

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