带头结点单链表的建立

来源:互联网 发布:数据恢复软件哪个好 编辑:程序博客网 时间:2024/05/22 04:46
<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);}


                                             
0 0
原创粉丝点击