逆轉單向鏈表

逆轉單向鏈表

#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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章