使用结构和指针

《C与指针》读书笔记
1.链表
链表就是一些包含数据的独立数据结构(节点)的集合。链表中的每个节点通过链或指针连接起来。
2.单链表
typedef struct NODE {
struct NODE *link;
int value;
}
链表中的每个节点都有一个指向它的指针。对于第一个节点,这个指针是根指针。对于其他节点,这个指针是前一个节点的link字段。下面是有序链表,有root指针指向第一个节点,有三个节点分别是5、10、15。

现在准备将12插入到列表中。一开始由root指针访问到第一个节点,value = 5,小于12。继续往下走。

访问第二个节点,value = 10依然小于12。继续往下走。

访问第三个节点,value = 15大于12。找到插入位置。

下面是插入程序:
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 = &current->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;
}
3. 双链表
在一个双链表中,每个节点都包含两个指针——指向前一个节点的指针和指向后一个节点的指针。
下面是节点类型的声明。
typedef struct NODE{
struct NODE *fwd;
struct NODE *bwd;
int value;
} Node;
现在存在两个根指针:一个指向链表的第1个节点,另一个指向最后一个节点。根指针分开声明相对较为麻烦,我们把它们放到一起作为一个节点,但是它的值不会被使用。这样一个根节点,它的fwd字段指向链表的第1个节点,它的bwd字段指向链表的最后一个节点。如果链表为空,这两个字段都为NULL。

下面是插入函数:
int
dll_insert( register Node *rootp, int value )
{
register Node *this;
register Node *next;
register Node *newnode;

/*
** See if value is already in the list; return if it is.
** Otherwise, allocate a new node for the value ("newnode"
** will point to it). "this" will point to the node that the
** new value should follow, and "next" will point to the one
** after it.
*/
for( this = rootp; (next = this->fwd) != NULL; this = next ){
if( next->value == value )
return 0;
if( next->value > value )
break;
}
newnode = (Node *)malloc( sizeof( Node ) );
if( newnode == NULL )
return -1;
newnode->value = value;

/*
** Add the new node to the list.
*/
newnode->fwd = next;
this->fwd = newnode;

if( this != rootp )
newnode->bwd = this;
else
newnode->bwd = NULL;

if( next != NULL )
next->bwd = newnode;
else
rootp->bwd = newnode;

return 1;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值