码迷,mamicode.com
首页 > 其他好文 > 详细

逆转单向链表

时间:2014-10-24 19:10:08      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:逆转   链表   反转   

逆转单向链表

#include <stdio.h>
#include <stdlib.h>
struct Node {
	int data;
	struct Node *next;
};

void list_reverse(struct Node **head)
{
	struct Node *cur, *rev;
	struct Node *hold;
	cur = *head;
	rev = 0;
	while (cur) {
		hold = cur;
		cur = cur->next;
		hold->next = rev;
		rev = hold;
	}
	*head = rev;
}

void list_print(const struct Node *head)
{
	while (head) {
		printf("%d ", head->data);
		head = head->next;
	}
	printf("\n");
}

void list_push(struct Node **head, int data)
{
	struct Node *node;
	node = (struct Node *)malloc(sizeof(struct Node));
	if (!node) return;
	node->data = data;
	node->next = *head;
	*head = node;
}

void list_clear(struct Node **head)
{
	struct Node *cur, *hold;
	cur = *head;
	while (cur) {
		hold = cur;
		cur = cur->next;
		free(hold);
	}
	*head = 0;
}

int main()
{
	struct Node *list = 0;
	
	list_push(&list, 1);
	list_push(&list, 3);
	list_push(&list, 5);
	list_push(&list, 7);
	list_push(&list, 9);
	
	list_print(list);
	list_reverse(&list);
	list_print(list);
	list_clear(&list);
	return 0;
}


本文出自 “chhquan” 博客,请务必保留此出处http://chhquan.blog.51cto.com/1346841/1567617

逆转单向链表

标签:逆转   链表   反转   

原文地址:http://chhquan.blog.51cto.com/1346841/1567617

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!