【数据结构】链式存储单链表


数据结构单链表的链式存储实现


//======================================================================  
//  
//        Copyright (C) 2014-2015 SCOTT      
//        All rights reserved  
//  
//        filename: List.c
//        description: a demo to display SeqList
//  
//        created by SCOTT at  01/28/2015 
//        http://blog.csdn.net/scottly1
//  
//======================================================================  

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

#define TRUE	1
#define FALSE	1

typedef int Status;
typedef int ElementType;

typedef struct _tag_Node
{
	ElementType data;
	struct _tag_Node *next;
}NODE, *PNODE;


PNODE initList()
{
	int i, j = 0;
	int nLen;
	PNODE pHead = NULL;
	PNODE pNode = NULL;	

	printf("Input The Length:");
	scanf("%d", &nLen);

	pHead = (PNODE)malloc(sizeof(NODE));
	pHead->data = nLen;                      // 头结点数据域可用于存储如链表长度等信息。
	pHead->next = NULL;

	for(i=0; i<nLen; ++i, ++j)
	{
		pNode = (PNODE)malloc(sizeof(NODE));
		printf("Input The %d val:", nLen-j);
		scanf("%d", &(pNode->data));

		pNode->next = pHead->next;           // 注意链表的生成技巧!
		pHead->next = pNode;
	}

	return pHead;
}


Status traverseList(PNODE list)
{
	int i = 1;
	PNODE p = list->next;
	ElementType data;

	while(p)
	{
		data = p->data;
		printf("The %d Data is:%d\n", i++, data);
		p = p->next;
	}

	printf("The Length of List is %d\n\n", list->data);

	return TRUE;
}


Status deleteNode(PNODE list, int pos, PNODE ret)
{
	int i = 0;
	PNODE pHead = list;
	PNODE pTmp =  NULL;

	if(!pHead || pos <=0 || pos >pHead->data)
	{
		return FALSE;
	}

	while(pHead->next && i<pos-1)
	{
		pHead = pHead->next;
		i++;
	}

	if(!pHead || i>pos-1)
	{
		return FALSE;
	}

	pTmp = pHead->next;
	pHead->next = pTmp->next;
	free(pTmp);
	--list->data;

	return TRUE;
}


Status insertNode(PNODE list, int pos, PNODE node)
{
	int i = 0;
	PNODE pHead = list;

	if(!pHead || pos <=0) //pos >pHead->data
	{
		return FALSE;
	}

	while(pHead->next && i<pos-1)
	{
		pHead = pHead->next;
		++i;
	}

	node->next = pHead->next;
	pHead->next = node;
	++list->data;

	return TRUE;
}


int main()
{
	PNODE list;
	PNODE ret;
	PNODE node;

	list = initList();
	traverseList(list);

	// 删除测试
	deleteNode(list, 2, ret);
	traverseList(list);

	// 插入测试
	node = (PNODE)malloc(sizeof(NODE));
	node->data = 100;
	insertNode(list, 0, node);    // not success
	insertNode(list, 1000, node); // insert in last
	traverseList(list);

	return 0;
}

注:原创文章,转载请注明出处:http://blog.csdn.net/scottly1/article/details/43247465


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值