单链表的反转
这个系列的第一篇,用单链表做一个开始。有定义单链表、生成单链表和单链表反转构成
单链表
单链表定义,参见百度。
简要的说,每个结点构成:元素+指针。(用代码来说)
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纳入了整个博客中