[日常] 算法-單鏈表的創建-尾插法
阿新 • • 發佈:2018-06-11
HP 遍歷 覆蓋 分配內存 public PE malloc 32位系統 lin
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 main import( "fmt" ) type Node struct{ data string next *Node } type LinkList *Node func 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語言版:
<?php class 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"; }
[日常] 算法-單鏈表的創建-尾插法