標籤:第一個 c語言 include \n ++ aaa null def 單鏈表
1.建立頭結點,頭結點的next指向null
2.把頭結點賦值給一個中間變數
3.迴圈中建立結點, 中間變數的next指向新結點
4.新結點覆蓋中間變數
c語言版:
#include <stdio.h>#include <stdlib.h>typedef struct Node{ char* data; struct Node* next;} Node;typedef Node* LinkList;int main(){ //指標所佔位元組與系統有關,一般32位系統,一個指標佔4個位元組 printf("%d\n",sizeof(Node));//輸出 4+4=8 //頭結點 LinkList head=(LinkList)malloc(sizeof(Node)); //第一個結點 Node* node1=(Node*)malloc(sizeof(Node)); node1->data="aaa"; node1->next=NULL; //第二個結點 Node* node2=(Node*)malloc(sizeof(Node)); node2->data="bbb"; node2->next=NULL; head->next=node1; node1->next=node2; //遍曆 while(head->next){ head=head->next; printf("%s\n",head->data); } //2.尾插法 LinkList list=(LinkList)malloc(sizeof(Node)); list->next=NULL; LinkList temp=list;//中間過渡 for(int i=0;i<10;i++){ LinkList node=(LinkList)malloc(sizeof(Node)); char* str=(char*)malloc(4);//給字串分配記憶體 sprintf(str,"aaa%d",i); node->data=str; temp->next=node; temp=node;//迴圈的時候,每次覆蓋成最新的結點 } //遍曆 while(list->next){ list=list->next; printf("%s\n",list->data); } }
go語言版:
package mainimport( "fmt")type Node struct{ data string next *Node}type LinkList *Nodefunc main(){ list:=new(Node) list.next=nil var node LinkList temp:=list for i:=0;i<10;i++{ node=new(Node) node.data="aaa"+fmt.Sprintf("%d",i) node.next=nil temp.next=node temp=node } //遍曆 for{ list=list.next fmt.Println(list.data) if list.next==nil{ break } } }
php語言版:
<?phpclass Node{ public $data; public $next;}//尾插法$list=new Node();$list->next=null;$temp=$list;for($i=0;$i<10;$i++){ $node=new Node(); $node->data="aaa{$i}"; $node->next=null; $temp->next=$node; $temp=$node;}//遍曆while($list->next){ $list=$list->next; echo $list->data."\n";}
[日常] 演算法-單鏈表的建立-尾插法