链表简易原理入门

来源:互联网 发布:优酷总是网络连接失败 编辑:程序博客网 时间:2024/05/29 13:11

链表是一种数据处理思想, 可以将零散的数据串联起来.
[单向]链表就好比一个很长的队伍,队伍里的人需谨记排在它后面的人是谁,那么带队者只需要找到队伍的第一个人, 然后顺藤摸瓜就可以将整个队伍的所有人都找齐了. 我们将这第一个人称为”表头”,它代表是这个链表的开始地址.

#include "stdafx.h" //header for VC#include<stdio.h>#include<stdlib.h>/*定义链表结构体类型*/typedef struct TagList{    int val;    struct TagList *next;}List;/*创建链表*/List* create_list(int val){    List *head = new List;    if(NULL == head)    {        return NULL;    }    head->val = val;    head->next = NULL;    return head;}/* 插入节点数据(倒插) */List* insert_TagList(List *head, int val){    List *temp;    if(NULL == head)    {        return NULL;    }    temp = new List;    temp->val = val;    temp->next = head;    head = temp;    return head;}/* 插入节点数据(顺插) */List* insert_TagList_2(List *head, int val){    List *temp;    List *st;    if(NULL == head)    {        return NULL;    }    temp =new List;    temp->val = val;    temp->next=NULL ;    st=head;     while (st!=NULL)    {        if (st->next==NULL)        {          st->next=temp;          break;        }else        {            st=st->next;        }    }    return st;}/*删除链表*/void delete_list(List *head){    List *temp = NULL;    if(head != NULL)    {        temp = head;        head = head->next;        free(temp);        temp = NULL;        delete_list(head);    }}/*删除一个节点的数据为d的节点*/List *delete_node(List * head, int d){    List *temp = head;    if(head != NULL)    {        if(head->val == d)        {            temp = head;            head = head->next;            delete temp;            temp = NULL;        }        else        {            temp = head->next;            if(temp != NULL)            {                temp = delete_node(temp,d);                head->next = temp;            }        }    }    return head;}/************************************************************* 主测试函数, 注意数据的顺插和倒插在查询数据时是稍有不同的 * 倒序插入数据时,第一个插入的数据head其实就变成了链表的尾巴Tail.***********************************************************/int main(void){    int i = 0;    List * head = create_list(100); //初始化数据100    List * buf;    for(i = 1; i <= 10; i++)    {        head = insert_TagList(head, 100+i); //倒序插入101到110    }    ///将链表的数据,倒序打印出来     i=0;     buf=head;     while (buf!=NULL)     {         printf("\r\n Data[%02d]: %d",i++,buf->val);         buf=buf->next;     }    getchar();//stop watch for VC    return 0;}
1 0
原创粉丝点击