1. 程式人生 > 其它 >字元申明_NOIP模擬賽(十)出鍋申明

字元申明_NOIP模擬賽(十)出鍋申明

技術標籤:資料結構

1.什麼是單鏈表

單鏈表其實就是由一個數據域和一個指標所組成的結構體,資料域是用來存放你所要儲存的資料,指標就是用來儲存你所要儲存資料的下一個節點指標。

單鏈表的程式碼格式

typedef struct LNode{
 int data;
 struct LNode *next;
} LNode,*LinkList; 

2.單鏈表的建立

單鏈表的建立其實有兩種方式,一種是頭插法(讓新來的節點先有所指向),他的遍歷連結串列的順序就與你說插入的資料的順序相反,還有一種就是尾插法,遍歷的順序就與你所插入的資料的順序相同的。

LinkList createList(LinkList &head){
 cout<<"請插入帶插入的節點的資料,輸入0結束本次連結串列的建立"<<endl;
 
 LinkList temp;//每次插入資料所用的新的節點 
 int data;
 head = (LinkList)malloc(sizeof(LNode));
 head->next = NULL;
  cin>>data;
 //假設以 0 為建立連結串列結束 
 while(data != 0){
  
  //輸入新的資料後建立的節點指標 
  temp  = (LinkList)malloc(sizeof(LNode));
  temp->data = data;    //語句1     //設定資料域
   
   //先插入的節點指標先有所指向
   temp->next = head->next;  //
   head->next = temp;
    
    cin>>data;
 }
  
  return head;
}

3完整程式碼

#include<iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;

typedef struct LNode{
 
 int data;
 
 struct LNode *next;
} LNode,*LinkList; 

// pList &head 指標的引用 
LinkList createList(LinkList &head){
 cout<<"請插入帶插入的節點的資料,輸入0結束本次連結串列的建立"<<endl;
 
 LinkList temp;//每次插入資料所用的新的節點 
 int data;
 head = (LinkList)malloc(sizeof(LNode));
 head->next = NULL;
  cin>>data;
 //假設以 0 為建立連結串列結束 
 while(data != 0){
  
  //輸入新的資料後建立的節點指標 
  temp  = (LinkList)malloc(sizeof(LNode));
  temp->data = data;    //語句1     //設定資料域
   
   //先插入的節點指標先有所指向
   temp->next = head->next;  //語句1 
   head->next = temp;  //
    
    cin>>data;
 }
  
  return head;
}

void printList(LinkList head){
	int i =0;
	head = head->next;
	while(true){
	  if(head->next == NULL){
	  	cout<<head->data;
	  	break;
	  }
	  if(head->next != NULL){
	  	cout<<head->data<<",";
	  	head = head->next;
	  } 
	}
}

int main(){
 //指標 
 LinkList head;
 head = createList(head);

 //遍歷連結串列 
  printList(head);
  
 return 0;
 
}