【数据结构和算法实践-单链表的反转】

单链表的反转

这个系列的第一篇,用单链表做一个开始。有定义单链表、生成单链表和单链表反转构成

单链表

单链表定义,参见百度。
简要的说,每个结点构成:元素+指针。(用代码来说)

public class Node {

    public int value;
    public Node next;
    
    public Node(int value){
        this.value =value;
    }
}

单链表生成

生成单链表。核心是指针赋值和节点赋值,用pre作为一个中间变量。要特别关注的是,需要有一个链表的head,整个链表也需要从head开始,即return是head。

    public static Node generateRandomLinkedList(int len ,int value){
        Node head = null;
        Node pre = null;
        while (len!=0){
            Node current =new Node((int)(Math.random()*(value+1)));
            if(head == null){
                head = current;
                pre = head;
            }else{
                pre.next = current;
                pre =current;
            }
            System.out.println("put in node is >>>"+pre.value);
            len--;
        }
        return head;
    }

单链表反转

反转就是让链尾变成head,那么从第一个元素和指针开始遍历,让指针指向上一个,让元素变成下一个(即head)。
Java代码如下

    public static Node reverserLinkedList(Node head){
        Node pre = null;
        Node next = null;
        while (head != null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

Rust代码如下

impl Solution {
    pub fn reverse_list(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        let mut res = None;
        while let Some(mut node) = head {
            head = node.next.take();
            node.next = res;
            res = Some(node);
        }
        res
    }
}

反思&总结

第一篇不知道咋样,其实如果真的是实践的话,应该是从数组构建开始,权且当作一个复习吧~~
Log:2024-08-27 团队将rust纳入了整个博客中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值