您的位置:首页 > 理论基础 > 数据结构算法

数据结构 单链表的创建 插入 删除

2009-07-29 13:27 423 查看
单链表比较简单,没什么好说的,直接上代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NUM 10

typedef struct _chbList
{
int data;
struct _chbList *next;
}chbList;

/**
*  pList:链表添加至末尾
*  时间:2009.7.29
*/
int AddTail( chbList *pList,  chbList *pTail )
{
if( pList == NULL || pTail == NULL )
return 0;
while( pList->next )
{
pList = pList->next;
}
pTail->next = NULL;
pList->next = pTail;
return 1;
}
/**
*  pList:链表根据位置插入到链表位置
*  时间:2009.7.29
*/
int InsertValue( chbList *pList, chbList *insert, int seq )
{
if( pList == NULL || insert == NULL )
return 0;
int i = 0;
while( pList && i < seq-1	)
{
pList = pList->next;
i++;
}
insert->next = pList->next;
pList->next = insert;
return 1;
}
/**
*  pList:链表根据位置删除链表
*  时间:2009.7.29
*/
int DeleteValue( chbList *pList, int seq )
{
if( pList == NULL )
return 0;
chbList *pT;
int i = 0;
while( pList && i < seq-1 )
{
pList = pList->next;
i++;
}
pT = pList->next;
pList->next = pT->next;
free( pT );
return 1;
}

int main( void )
{
chbList *pList,*pTemp;
int i;

pList = ( chbList * )malloc( sizeof( chbList ) );
pList->next = NULL;
pList->data = 0;

for( i = 0; i < NUM-1; i++ )
{
pTemp = ( chbList * )malloc( sizeof( chbList ) );
AddTail( pList, pTemp );
pTemp->data = i+1;
}
chbList *insert = ( chbList * )malloc( sizeof( chbList ) );
insert->data = -1;
InsertValue( pList, insert, 4 );

DeleteValue( pList, 2 );

while( pList )
{
printf( "%d ", pList->data );
pList = pList->next;
}
while( pList )
{
free( pList );
pList = pList->next;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: