表:链表

来源:互联网 发布:iis绑定域名 编辑:程序博客网 时间:2024/06/07 00:50

整理一下硬盘里关于链表的知识,温故而知新。

链表是一种物理存储单元上非连续、非顺序的存储结构。其特点是有头尾结点,除头结点外,其它结点都只有一个前驱,除尾结点外,其它结点都只有一个后继。


常见的链表有单向链表,双向链表,循环链表。


单向链表的结构一般这样写

typedef struct listnode{        int val;        struct listnode *next;}List;

一般来说链表的结构体只包含一个数据,一个指向后继结点的指针。如果是树或双链表,结构体会多一个指针。

单向链表的操作:

创建链表

List* create_list(int val){        List *head = (List *)malloc(sizeof(List)/sizeof(char));        if(NULL == head)        {                return NULL;        }        head->val = val;        head->next = NULL;        return head;}

插入结点

List* insert_listnode(List *head, int val){        List *temp;        if(NULL == head)        {                return NULL;        }        temp = (List *)malloc(sizeof(List)/sizeof(char));        temp->val = val;        temp->next = head;        head = temp;        return head;}

删除链表

void delete_list(List *head){        List *temp = NULL;        if(head != NULL)        {                temp = head;                head = head->next;                free(temp);                temp = NULL;                delete_list(head);        }}

统计节点个数

int count_listnode(List *head){        static int count = 0;            if(NULL != head)        {                 count += 1;                if(head->next != NULL)                {                         count_listnode(head->next);                }                 return count;        }}

顺序打印

void fdprint_listnode(List *head){        if(NULL != head)        {                printf("%d\t",head->val);                if(head->next != NULL)                {                        fdprint_listnode(head->next);                }        }}

反向打印(面试题常出)

void bkprint_listnode(List *head){        if(head != NULL)        {                if(head->next != NULL)                {                        bkprint_listnode(head->next);                }                printf("%d\t",head->val);        }}

用递归的代码看起来很简洁,但有个问题;当链表非常长的时候,就会导致函数调用的层级很深,从而有可能导致函数调用栈溢出。显式用栈基于循环实现的代码的鲁棒性要好一些。

void bkprint_listnode(List *pHead){std::stack<List*> nodes;List* pNode = pHead;        while(pNode != NULL){nodes.push(pNode);pNode = pNode->pNext;}while(!nodes.empty()){pNode = nodes.top();printf("%d\t",pNode->val);nodes.pop();}}


参考:

http://blog.chinaunix.net/uid-20937170-id-3313235.html


0 0
原创粉丝点击