雙向循環鏈表

要求實現用戶輸入一個數使得9個數字的排列發生變化,例如用戶輸入3,輸出結果:

345678912

同時需要支持負數,例如用戶輸入-3,輸出結果:

765432198

#include<stdio.h>
#include<malloc.h>
	struct dualnode
	{
		 int data;     //elementype表示一種數據類型,可能是int/char等等
	 struct dualnode *next;   //next 指針,用於鏈表結構指向下一個節點
		struct dualnode *prior;
	};
	typedef struct dualnode dualnode; //重定義struct node類型爲node

	dualnode* Creat(int n);
	int main()
	{
		dualnode* head;
		head = Creat(9);
		int i = 9;
		int n;
		scanf("%d",&n);
		int j = n;
		if(n == 0)
		{
			printf("error");
			return 0;
		}
		while(i)
		{
		//	printf("%d",head->data);
		//	head = head->prior;
			if(n > 0)
			{
				while(n-1)
				{
					head = head->next;
					n--;
				}
			}
			else	if(n < 0)
			{
				while(n)
				{
					head = head->prior;
					n++;
				}
			}
			if(j > 0)
			{
				printf("%d",head->data);
				head = head->next;
			}
			else
			{
				printf("%d",head->data);
				head = head->prior;
			}
			i--;
		}		
		return 0;
	}
	dualnode* Creat(int n)
	{
		dualnode *p = NULL;
		dualnode *head;
		head =(dualnode *)malloc(sizeof(dualnode));
		p = head;
		dualnode *s;
		int i = 1;
		if(0 != n)
		{
			while(i <= n)
			{
				s = (dualnode*)malloc(sizeof(dualnode));
				s->data = i;
				p->next = s;
				s->prior = p;
				p = s;
				i++;
			}
			s->next = head->next;
			head->next->prior = s;
		}
		free(head);
		return s->next;
	}



發佈了41 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章