1. 程式人生 > >資料結構 連結串列的建立,求連結串列的長度,插入元素等操作程式碼展示

資料結構 連結串列的建立,求連結串列的長度,插入元素等操作程式碼展示

 今上午老師佈置的作業,很不情願的寫了個單鏈表。。。發現長時間不寫確實很難一步寫對,除錯了20分鐘,可算是寫完了,

感覺應該是對了,測了幾組資料沒啥問題.....

程式碼如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <malloc.h>
using namespace std;
//連結串列資料型別
struct List{
    int data;
    List * next;
};
//連結串列初始化
List* init()
{
    return NULL;
}
//連結串列的建立
List* Create (List* L)
{
    if(L)
    {
        printf("連結串列未初始化\n");
        return NULL;
    }
    L=(List*)malloc(sizeof(List));
    L->next=NULL;
    printf("請輸入連結串列長度: ");
    int len;
    List* p=L;
    scanf("%d",&len);
    printf("請按遞增的順序輸入元素\n");
    for (int i=0;i<len;i++)
    {
        int data;
        scanf("%d",&data);
        List* New=(List*)malloc(sizeof(List));
        New->data=data;
        New->next=NULL;
        p->next=New;
        p=New;
    }
    return L;
}
//求連結串列的長度
void List_Len (List* L)
{
    if(L==NULL)
    {
        printf("連結串列未建立\n");
        return;
    }
    int len=0;
    List* p=L->next;
    while (p)
    {
        p=p->next;
        len++;
    }
    printf("連結串列的長度為%d\n",len);
}
//遍歷單鏈表
void Traverse (List* L)
{
    if(L==NULL)
    {
        printf("連結串列未建立\n");
        return;
    }
    List* p=L->next;
    printf("連結串列元素如下:\n");
    while (p)
    {
        printf("%d%c",p->data,p->next==NULL?'\n':' ');
        p=p->next;
    }
}
//插入元素
bool Insert (List* L)
{
    if(L==NULL)
    {
        printf("連結串列還未建立\n");
        return false;
    }
    printf("請輸入想要插入的元素: ");
    int Data;
    scanf("%d",&Data);
    List* p=L;
    while (p->next&&p->next->data<Data)
    {
        p=p->next;
    }
    List* New=(List*)malloc(sizeof(List));
    New->data=Data;
    New->next=p->next;
    p->next=New;
    return true;
}
int main()
{
    List* Head;
    Head=init();
    Head=Create(Head);
    Traverse(Head);
    List_Len(Head);
    if(Insert(Head))
        printf("插入成功\n");
    else
        printf("插入失敗\n");
    Traverse(Head);
    List_Len(Head);
    return 0;
}
/*
執行結果如下:
請輸入連結串列長度: 3
請按遞增的順序輸入元素
1 2 3
連結串列元素如下:
1 2 3
連結串列的長度為3
請輸入想要插入的元素: 4
插入成功
連結串列元素如下:
1 2 3 4
連結串列的長度為4*/