带头结点单链表的建立

<pre name="code" class="cpp">#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct Node{
    int data;
    struct Node* next;
};

Node* CreatList(int n)
{
    if(n<0)
        return NULL;
    Node* head=(Node*)malloc(sizeof(Node));
    head->next=NULL;
    Node* move=head;
    for(int i=0;i<n;i++)
    {
        char Data;
        Node* node=(Node*)malloc(sizeof(Node));
        scanf("%c",&Data);
        node->data=Data;
        node->next=NULL;
        move->next=node;
        move=node;
    }
    return head;
}

int Destroy(Node* head)
{
    if(head==NULL)
        return -1;
    Node* nextNode=head->next;
    while(nextNode!=NULL)
    {
        free(head);
        head=nextNode;
        nextNode=nextNode->next;
    }
    free(head);
    return 0;
}

int InsertOneNode(Node *head,int index,Node *node)
{
    if(head==NULL||node==NULL||index<=0)
        return -1;
    int count=0;
    while(head!=NULL&&count<index-1)
    {
        head=head->next;
        count++;
    }
    if(head!=NULL)
    {
        Node* nextNode=head->next;
        node->next=nextNode;
        head->next=node;
        return 0;
    }
    else
        return -1;
}

int DeleteOneNode(Node *head,int index)
{
    if(head==NULL||index<=0)
        return -1;
    int count=0;
    while(head!=NULL&&count<index-1)
    {
        head=head->next;
        count++;
    }
    if(head!=NULL)
    {
        Node* nextNode=head->next;
        head->next=head->next->next;
        free(nextNode);
        return 0;
    }
    return -1;
}

void PrintList(Node *head)
{
    if(head==NULL)
        return;
    head=head->next;
    while(head!=NULL)
    {
        printf("%c-->",head->data);
        head=head->next;
    }
    putchar('\n');
}    

int main()
{
    Node* head=CreatList(5);
    if(head==NULL)
        return -1;
    PrintList(head);

    Node* node1=(Node*)malloc(sizeof(Node));
    node1->next=NULL;
    node1->data='X';
    InsertOneNode(head,3,node1);
    PrintList(head);

    Node* node2=(Node*)malloc(sizeof(Node));
    node2->next=NULL;
    node2->data='X';
    InsertOneNode(head,3,node2);
    PrintList(head);

    DeleteOneNode(head,2);
    PrintList(head);

    Destroy(head);
}



                
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页