C语言学习笔记之数据结构篇(一)

来源:互联网 发布:学唇语 唇唇欲动软件 编辑:程序博客网 时间:2024/05/22 09:42
链表(堆中)
(1)链表: 它由设计为大小合适的小的容器组成, 这些容器可根据需要链接在一起。
链表组件:链表由节点组成。每个节点内可放置指定的数据类型。
头节点: 其工作是管理链表的头。
尾节点: 初始时,头节点的 next 指针指向尾节点。
内部节点:存放数据类型。 


(2)链表的特点
a.非常重要的数据结构
在计算机系统中有广泛的应用
b.灵活
c.比数组节省空间,避免内存浪费。
d.访问比较慢
e.插入,删除,修改比较方便
f.操作比较复杂


(3)链表的分类
a.指针链接方式:
单向链表
双向链表
单向循环链表
双向循环链表
b.是否带头节点:
头指针不带头节点
头指针带头节点


(4)用结构(体)与指针可以实现链表。一个典型的链表由节点和链表头组成。

程序要做到:低耦合 高内聚

代码如下:

/* * linklist.c * *  Created on: 2011-12-2 *      Author: Betamark */#include<stdio.h>#include<stdlib.h>typedef int T;//nodetypedef struct _node {T data;//data areastruct _node *next;//pointer area} Node;//linklist header pointer//Node *head = NULL;//no head node,single linklist//前插,后插,中间插入//先创建一个节点,再将该节点插入void insert_front(Node **head,T d) {Node *p = malloc(sizeof(Node));p->data = d;p->next = head;head = p;}//后插void insert_tail(Node **head,T d) {Node *p = malloc(sizeof(Node));p->data = d;p->next = NULL;if (*head == NULL)*head = p;else {Node *q = *head;while (q->next != NULL) {q = q->next;}q->next = p;}}//遍历travelvoid travel(Node **head) {Node *p = *head;while (p != NULL) {printf("%d\t", p->data);p = p->next;}printf("\n");}//先保留头所指向的下一个节点的next中保留的地址//再将头当前指向的堆空间释放掉//接着将第一步保留地址付给头指针void clear(Node **head) {while (head != NULL) {Node *p = (*head)->next;free(*head);*head = p;}}//求链表的长度int size(Node **head) {Node *p = *head;int count = 0;while (p) {p = p->next;++count;}return count;}//判断链表是否为空int empty(Node **head) {return *head == NULL;}//查找给定数据的节点在链表中的位置int find(Node **head,T d) {int pos = 0;Node* p = *head;while (p != NULL) {if (p->data == d)return pos;p = p->next;++pos;}return -1;}//获得给定索引节点的地址Node* getPointer(Node **head,int pos) {Node* p = *head;int i;for (i = 0; p != NULL && i < pos; ++i) {p = p->next;}return p;}//删除指点节点void erase(Node **head,T d) {if (*head == NULL)return;int pos = find(head,d);if (pos == -1)return;if (pos == 0) {/*Node *r=head; head=head->next; free(r);*/Node *r = (*head)->next;free(*head);*head = r;return;}Node* p = getPointer(head,pos - 1);Node *q = p->next;p->next = q->next;free(q);}//更新节点数据void update(Node **head,T o, T n) {/*int pos = find(o); if (-1 == pos) return; Node *p = getPointer(pos); p->data = n;*/Node* p = *head;while (p != NULL) {if (o == p->data) {p->data = n;return;}p = p->next;}}//获得头节点的内容T getHeader(Node **head){if(*head==NULL){printf("no head\n");return -1;}return (*head)->data;}//获得尾节点的内容T getTail(Node **head){if(*head==NULL){printf("no tail\n");return -1;}Node *p=*head;while(p->next!=NULL){p=p->next;}return p->data;}int main() {Node* head=NULL;insert_front(&head,1);insert_front(&head,2);insert_front(&head,3);insert_tail(&head,0);insert_tail(&head,12);travel(&head);//printf("size=%d\n", size());//clear();//printf("if empty=%d\n", empty());//printf("size=%d\n", size());//printf("%d\n", find(3));//erase(3);//erase(12);//erase(2);update(&head,12, 88);travel(&head);printf("head=%d,tail=%d\n",getHeader(&head),getTail(&head));return 0;}



原创粉丝点击