您的位置:首页 > 其它

关于链表的总结(一套链表定义)

2014-12-30 20:08 274 查看
/*链表定义*/

typedef struct node *link;

struct node

{

int item;

link next;

};

/*结点内存分配

*数据项引用x->item,x->next

*

*/

link x=malloc(sizeof *x);x->itme=1;x->next=NULL;

/*删除结点,t为删除结点指针,

**

**下面两种方式使用区别是:如果知道删除节点指针为t,则用t=x->next;x->next=t->next;free(t);否则另一个更好。

*/

t=x->next;x->next=t->next;free(t);

或者x->next=x->next->next;

/*插入结点,t为插入结点指针*/

t->next=x->next;x->next=t;

/*单链表遍历,跟数组循环for(i=0;i<N;i++)一样*/

for(t=x;t!=NULL;t=t->next)visit(t->item);

/************************************

**链表中头和尾节点/指针几种常规用法**

*************************************

************************************/

/*循环链表,永远非空(循环链表是最后一个节点又指回第一个节点的单链表,它是一种特殊的单链表)

**

**头插入(当前只有一个结点):head -> next = head;

**

**在x节点后插入t节点:t -> next = x -> next; x -> next = t;

**

**删除x后的节点: x -> next = x -> next -> next;

**

**遍历循环:t = head;

do { ... t = t -> next;} while (t != head);

**

**测试是否只有一个元素:if(head -> next == head)

*/

/*头指针,尾节点为空(就是带头指针单链表)

**

**初始化: head = NULL;

**

**在x节点后插入t节点:if (x == NULL) {head=t; head -> next = NULL;}

else {t -> next = x -> next; x->next = t;}

**

**删除x后的节点:t = x -> next; x -> next = t -> next;

**

**遍历循环:for (t = head; t != NULL; t = t -> next)

**

**测试表是否为空: if (head == NULL)

*/

/*有哑元头节点,尾节点为空(就是带头节点单链表)

**

**定义:有时在单链表的第一个结点之前附设一个结点,称之为头结点 。

头结点的数据域可以不存储任何信息,也可以存储如线性表长度等类的附加信息,

头结点的指针域存储指向第一个结点的指针

**

**初始化:head = malloc (sizeof *head)

head -> next = NULL;

**

**在x节点后插入t节点:t -> next = x -> next; x -> next = t;

**

**删除x后的节点:t = x -> next; x -> next = t -> next;

**

**遍历循环:for (t = head -> next; t != NULL; t = t -> next)

**

**测试表是否为空: if (head -> next == NULL)

*/

/*有哑元头节点,尾节点

**

**初始化:head = malloc (sizeof *head)

z = malloc(sizeof *z);

head -> next = z; z -> next = z;

**

**在x节点后插入t节点:t -> next = x -> next; x -> next = t;

**

**删除x后的节点:x->next=x->next->next

**

**遍历循环:for (t = head -> next; t != z; t = t -> next)

**

**测试表是否为空:if (head -> next == z)

*/

双向链表

/*定义*/

typedef struct node *link;

struct node

{

int item;

link next;

link prev;

};

/*节点x后插入给定节点t:t -> next = x -> next; x -> next -> prev = t;

x -> next = t; t ->prev = x;

**

**删除给定节点t:t -> next -> prev = t -> prev; t -> prev -> next = t -> next;

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: