现在的位置: 首页 > 综合 > 正文

线性链表(代码)

2013年02月26日 ⁄ 综合 ⁄ 共 1397字 ⁄ 字号 评论关闭
// 链表定义

#define status int
#define type int
#define format "%d"

#define OK 1
#define ERROR -1
#define FAIL 0

typedef struct NODE
{
	type data;
	NODE *next;
}NODE, *LINKLIST, *LINKPOI;
// 链表产生

status createLinkList(LINKLIST &LList, int n, type *element)
{
	// if link list is not NULL
	if(LList)
		return ERROR;

	if(n < 1 || !element)
		return FAIL;

	LINKPOI p, q = NULL;
	
	int i;

	for(i = n; i > 0; i--)
	{
		p = (NODE*)malloc(sizeof(NODE));
		p->next = q;
		p->data = *(element+i-1);
		q = p;
	}

	LList = p;
	return OK;
}
        // 补充链表元素输入

	int length = 0;
	type tempElement, *element;
	printf("***input element and end of\"0\"***\n\n");
	while(OK)
	{
		printf("*element[%d]: ", length+1);

		scanf(format, &tempElement);

		if(tempElement == 0)
			break;
		if(length == 0)
		{
			element = (type *)malloc(sizeof(type));
		}
		
		element = (type *)realloc(element, (length+1) * sizeof(type));
		
		*(element+length) = tempElement;
		length++;
	}
// 反转链表(1): 共三个指针previous, current, next,存储遍历过程中当前cureent指针
// 指向的下一个元素,将当前指针反转后,利用已经存储的指针往后面继续遍历。

status reverseLinkList(LINKLIST &LList)
{	
	if(!LList)
		return ERROR;

	LINKPOI previous, next, current;
	previous = NULL;
	current = LList;
	next = current->next;
	
	while(next)
	{
		current->next = previous;
		previous = current;
		current = next;
		next = current->next;
	}
	
	current->next = previous;
	LList = current;

	return OK;
}
// 反转链表(2) 只使用两个辅助指针p,q,头指针始终指向新链表第一个结点
// 开始时,先将第一个指针作为最后一个结点(p)断开连接,p,q后移,第二个节点(p)断开
// 将第一个节点(LList)挂在第二个后头指针从第一个指向第二个,p,q后移,循环往后移动即可

int convertList(LINKLIST &LList)
{
	LINKPOI p, q;
	p = List;
	q = p->next;

	p->next = NULL;
	p = q; 
	q = q->next;
	while(p->next)
	{
		p->next = List;
		List = p;		
		p = q;			
		q = q->next;
	}
	p->next = List;
	LList = p;
	return OK;
}

抱歉!评论已关闭.