您的位置:首页 > 编程语言 > C语言/C++

C语言笔试题(8)——链表逆序

2012-03-27 22:13 309 查看
#include <stdio.h>
#include <stdlib.h>

struct node
{
	int num;
	struct node *next;
};

struct node *create_list(void)
{
	struct node *head;

	head = (struct node *)malloc(sizeof(struct node));

	head->next = NULL;

	return head;
}

void insert_list(struct node *head, int value)
{
	struct node *p;

	p = (struct node *)malloc(sizeof(struct node));

	p->num = value;

	p->next = head->next;
	head->next = p;

	return;
}

void printf_list(struct node *head)
{
	struct node *p = head->next;

	while(p != NULL)
	{
		printf("%d\t", p->num);
		
		p = p->next;
	}

	printf("\n");

	return;
}

int reverse_list(struct node *head)
{
	struct node *p = head->next;
	struct node *q = head->next;

        if (head == NULL)
                 return -1;

	head->next = NULL;

	while(p != NULL)
	{
		q = q->next;
		
		p->next = head->next;
		head->next = p;

		p = q;
	}

	return 0;
}

int main(void)
{
	struct node *head;
	int i;

	head = create_list();

	for(i = 10; i > 0; i--)
	{
		insert_list(head, i);
	}

	printf("Change before:\n");
	printf_list(head);

	reverse_list(head);

	printf("Change later:\n");
	printf_list(head);

	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: