數據結構 雙鏈表初始化

#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct Node2{
	int num;
	Node2 *next;
	Node2 *pre;
}Node2;//定義節點
void init(Node2 *head,int len){//初始化鏈表長度
	Node2 *head2=head;
	for(int i=0;i<len;i++){//尾插法
		Node2 *node=(Node2 *)malloc(sizeof(Node2));//創建一個節點,因爲是malloc函數分配,分配的空間並不會因爲函數運行結束而結束
		node->num=i;//給節點賦值
		head2->next=node;//將新節點的地址會給上一個節點的next,形成鏈表
		node->pre=head2;//指向前一個節點
		head2=node;//移動到新節點,也就是最後一個節點,然後繼續循環
	}
	head2->next=NULL;//最後一個節點,next的值要爲NULL

}

void print(Node2 *head){
	//從前面打印
	Node2 *head1=head->next,*back;//頭結點沒有數值,所以先移動到下一個節點
	while(head1!=NULL){
		cout<<head1->num<<" ";
		back=head1;
		head1=head1->next;//移動到下一個節點
	}
	cout<<endl;
	//從後面打印
	Node2 *head2=back;
	while(head2!=NULL){
		if(head2->pre!=NULL)cout<<head2->num<<" ";//不要把頭結點的值讀出來
		head2=head2->pre;//移動到前一個節點
	}
	cout<<endl;
}

int main(int argc, char const *argv[]){
	Node2 *head=(Node2 *)malloc(sizeof(Node2));
	head->next=NULL;
	head->pre=NULL;

	//雙向鏈表應該沒有必要糾結用頭插法或者尾插法
	/*
		輸入:傳入頭節點,初始化的長度
		返回:空
	*/
	init(head,5);

	/*
		輸入:傳入頭節點,初始化的長度
		打印結果
		返回:空
	*/
	print(head);


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