单向链表(还没有借鉴其他的实现方法)

来源:互联网 发布:python re 替换一部分 编辑:程序博客网 时间:2024/05/18 03:44

单向链表的5个操作:建立,输出,删除,在第i个点后加入新点,删除第i个点,编译环境是codeblocks

#include <stdio.h>#include <stdlib.h>struct node{    int data;    node *next;};node *creatList(int n){    int temp;    node *head, *tail, *p;    head = (node*)malloc(sizeof(node));    tail = head;            //头尾相同,那么就可以往tail后面一直加,最后                        for(int i=0; i<n; i++)  //tail就是尾,head就是头,注意head是用来辅助的    {        scanf("%d",&temp);        p = (node*)malloc(sizeof(node));        p->data = temp;        p->next = NULL;        tail->next = p;        tail = p;         //插入到tail后,即从head开始一直往后连接    }    return head;}void print(node *head){    head = head->next;    while(head != NULL)    {        printf("%d ", head->data);        head = head->next;    }    printf("\n");}void deleteList(node *head){    node *p = head;    while(p != NULL)    {        p = p->next;        head = p->next->next;        free(p);    }    free(head);}void insertNode(node *head, node *newNode, int flag)  //插入第flag个后面{    node *p;    p = head;    for(int i=0; i<flag && p!=NULL; i++)  //寻找第flag个节点    {        p = p->next;    }    newNode->next = p->next;    p->next = newNode;}void deleteNode(node *head, int flag)  //删除第flag个节点{    node *p, *q;    p = head;    for(int i=1; i<flag && p!= NULL; i++)  //寻找第flag-1个节点    {        p = p->next;    }    q = p->next;    p->next = q->next;    free(q);}int main(){    int n;    while(scanf("%d",&n)!=EOF)    {        node aha = {111111, NULL};        /*建表并且输出这个表*/        node *head = creatList(n);        print(head);        /*在第二个节点后插入节点aha,并输插入后的表*/        insertNode(head, &aha, 2);        print(head);        /* 删除第二个节点并输出表*/        deleteNode(head, 2);        print(head);        /*摧毁这个表*/        deleteList(head);    }    return 0;}

如有错误欢迎指出

0 0