go语言、rust、c语言、php、node、zig分别实现链式操作

以下是AI分别实现Go语言、Rust、C语言、PHP、Node.js和Zig的链式操作代码示例:

Go语言

package main

import "fmt"

type IntList struct {
    value int
    next  *IntList
}

func (l *IntList) Add(value int) *IntList {
    node := &IntList{value: value, next: l}
    return node
}

func main() {
    list := &IntList{}
    list = list.Add(3).Add(2).Add(1)
    
    // 遍历链表
    for node := list; node != nil; node = node.next {
        fmt.Println(node.value)
    }
}

Rust

struct IntList {
    value: i32,
    next: Option>,
}

impl IntList {
    fn new() -> IntList {
        IntList { value: 0, next: None }
    }
    
    fn add(mut self, value: i32) -> IntList {
        let next = Some(Box::new(self));
        IntList { value, next }
    }
}

fn main() {
    let mut list = IntList::new();
    list = list.add(3).add(2).add(1);
    
    // 遍历链表
    let mut node = Some(&list);
    while let Some(n) = node {
        println!("{}", n.value);
        node = n.next.as_deref();
    }
}

C语言

#include 
#include 

typedef struct IntList {
    int value;
    struct IntList* next;
} IntList;

IntList* add(IntList* list, int value) {
    IntList* node = (IntList*)malloc(sizeof(IntList));
    node->value = value;
    node->next = list;
    return node;
}

int main() {
    IntList* list = NULL;
    list = add(add(add(list, 1), 2), 3);
    
    // 遍历链表
    IntList* node = list;
    while (node != NULL) {
        printf("%d\n", node->value);
        node = node->next;
    }
    
    return 0;
}

PHP

value = null;
        $this->next = null;
    }
    
    function add($value) {
        $node = new IntList();
        $node->value = $value;
        $node->next = $this;
        return $node;
    }
}

$list = new IntList();
$list = $list->add(3)->add(2)->add(1);

// 遍历链表
$node = $list;
while ($node != null) {
    echo $node->value . "\n";
    $node = $node->next;
}
?>

Node.js

class IntList {
    constructor() {
        this.value = null;
        this.next = null;
    }
    
    add(value) {
        const node = new IntList();
        node.value = value;
        node.next = this;
        return node;
    }
}

let list = new IntList();
list = list.add(3).add(2).add(1);

// 遍历链表
let node = list;
while (node !== null) {
    console.log(node.value);
    node = node.next;
}

Zig

const std = @import("std");

pub const IntList = comptime struct {
    value: i32,
    next: ?*IntList,
};

pub fn add(list: ?*IntList, value: i32) ?*IntList {
    var node: [*]IntList = &[_]IntList{
        .{ .value = value, .next = list },
    };
    return &node[0];
}

pub fn main() !void {
    var list: ?*IntList = null;
    list = add(add(add(list, 1), 2), 3);
    
    // 遍历链表
    var node: ?*IntList = list;
    while (node) : (node = node.*next) {
        std.debug.print("{d}\n", .{node.*value});
    }
    
    return try std.io.getWriter().flush();
}

这些是链式操作的简单示例,用于介绍不同语言的链式操作概念,并不代表完整的链表数据结构的实现。具体的实现方式可能根据需求和语言特性有所差异。

本文由mdnice多平台发布

你可能感兴趣的:(后端)