加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[日常] 算法-单链表的创建-尾插法

发布时间:2020-12-16 19:36:42 所属栏目:大数据 来源:网络整理
导读:1.创建头结点,头结点的next指向null 2.把头结点赋值给一个中间变量 3.循环中创建结点,中间变量的next指向新结点 4.新结点覆盖中间变量 c语言版: #include typedef struct Node{ char data; struct Node next; } Node; typedef Node LinkList; int main(){ //

1.创建头结点,头结点的next指向null

2.把头结点赋值给一个中间变量

3.循环中创建结点,中间变量的next指向新结点

4.新结点覆盖中间变量

c语言版:

#include

typedef struct Node{
char data;
struct Node
next;
} Node;
typedef Node LinkList;
int main(){
//指针所占字节与系统有关,一般32位系统,一个指针占4个字节
printf("%dn",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("%sn",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("%sn",list->data);
    }   

}

go语言版:

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语言版:

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";
}

  

  

  

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读