建立一個包含若干整數或隨機數的單向循環鏈表,然後通過某些算法,將其中的數據翻轉

更多資料請點擊:我的目錄
本篇僅用於記錄自己所學知識及應用,代碼仍可優化,僅供參考,如果發現有錯誤的地方,儘管留言於我,謝謝!
運行結果:
在這裏插入圖片描述

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

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

struct node *init_list()//創建帶頭節點鏈表
{
	struct node *head = malloc(sizeof(struct node));
	if(head != NULL)
	{
		head->next = head;
	}
	return head;
}

struct node *new_node(int data)//創建新節點並賦值
{
	struct node *new = malloc(sizeof(struct node));
	if(new != NULL)
	{
		new->next = new;
		new->data = data;
	}
	return new;
}

void link_list(struct node *head, struct node *new)//鏈接新節點
{
	if(head != NULL && new != NULL)
	{
		if(head->next == head)//判斷是否爲空
		{
			head->next = new;//將頭節點指向new
			new->next = head;//將new指向頭節點
			return;
		}
		struct node *tail = head;
		while(tail->next != head)
		{
			tail = tail->next;
		}
		tail->next = new;
		new->next = head;
	}
}

void show(struct node *head,int N)//輸出顯示
{
	if(N == 1)printf("變換前:");
	else printf("變換後:");

	if(head != head->next)
	{
		struct node *tail = head;
		while(tail->next != head )
		{
			tail =  tail->next;
			printf("%d\t",tail->data);
		}
	printf("\n");
	}
}

void over_turn(struct node *head)//鏈表元素前後翻轉
{
	if(head->next != head)
	{
		struct node *p = head->next;
		struct node *tail = p->next;
		while(tail != head)
		{
			p->next = tail->next;
			tail->next = head->next;
			head->next = tail;
			tail = p->next;
		}
	}
}

int main()
{
	struct node *head = init_list();//新建鏈表
	printf("請輸入將要插入的數據個數:");
	int n ;
	scanf("%d",&n);
	srand(time(NULL));//隨機值
	for(int i = 1; i <= n; i++)
	{
		//struct node *new = new_node(i);//創建新節點並賦值
		struct node *new = new_node(rand()%1000);//創建新節點並賦隨機值
		link_list(head, new);//鏈接新節點
	}
	show(head,1);
	over_turn(head);//鏈表元素前後翻轉
	show(head,2);
	return 0;
}

更多資料請點擊:我的目錄

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