原创文章,转载请注明出处:http://blog.csdn.net/yanghaoran321/article/details/7655099
1、链表就是一些包含数据的独立数据结构(通常称为节点)的集合;
2、链表中的节点可能分布于内存的各个地方,不一定是物理上相邻,单链表只能一个方向进行遍历;
3、在对链表的操作过程中,应该注意以下几点:
(1)动态分配内存时务必检查是否分配成功(检查返回值是否为NULL);
(2)操作的过程中,应该避免对NULL指针进行解引用,所以对于有可能出现NULL指针的地方都要进行判断;
4、对于单链表的插入操作:
typedef struct NODE {
struct NODE *link;
int value;
}Node;
把一个新节点链接到链表中需要两个步骤,首先,新节点的link字段必须设置为指向它目标后续节点,其次,前一个节点的link字段必须设置为指向这个新的节点;通常情况下,我们会采用保存一个指向前一个节点的指针来完成第二个步骤,然后这样会造成使插入到链表的起始位置成为一种特殊情况,需要单独处理;
在C语言中,我们可以通过保存一个指向必须进行修改的link字段的指针,而不是保存一个指向前一个节点的指针,从而消除这种特殊情况;
/*
** Insert into an ordered, singly linked list. The arguments are
** a pointer to the first node in the list, and the value to
** insert.
*/
#include <stdlib.h>
#include <stdio.h>
#include "sll_node.h"
#define FALSE 0
#define TRUE 1
int
sll_insert( register Node **linkp, int new_value )
{
register Node *current;
register Node *new;
/*
** Look for the right place by walking down the list
** until we reach a node whose value is greater than
** or equal to the new value.
*/
while( ( current = *linkp ) != NULL &&
current->value < new_value )
linkp = ¤t->link;
/*
** Allocate a new node and store the new value into it.
** In this event, we return FALSE.
*/
new = (Node *)malloc( sizeof( Node ) );
if( new == NULL )
return FALSE;
new->value = new_value;
/*
** Insert the new node into the list, and return TRUE.
*/
new->link = current;
*linkp = new;
return TRUE;
}