image.png
package hxy.bytecode.algorithm;
/**
* @author eric
*/
public class LinkReverse {
public static void main(String[] args) {
LinkNode linkNode5 = new LinkNode(5, null);
LinkNode linkNode4 = new LinkNode(4, linkNode5);
LinkNode linkNode3 = new LinkNode(3, linkNode4);
LinkNode linkNode2 = new LinkNode(2, linkNode3);
LinkNode linkNode = new LinkNode(1, linkNode2);
LinkNode reverse = reverse(linkNode);
System.out.println(reverse);
}
public static LinkNode reverse(LinkNode current) {
LinkNode pre = null, next;
while (current != null) {
next = current.next;
current.next = pre;
pre = current;
current = next;
}
return pre;
}
}
package hxy.bytecode.algorithm;
/**
* 链表结点
*
* @author eric
*/
public class LinkNode {
public int value;
public LinkNode next;
public LinkNode(int value, LinkNode next) {
this.value = value;
this.next = next;
}
}
Golang版本
package main
type LinkNode struct {
Value int
Next *LinkNode
}
func main() {
link5 := LinkNode{Value: 5, Next: nil}
link4 := LinkNode{Value: 4, Next: &link5}
link3 := LinkNode{Value: 3, Next: &link4}
link2 := LinkNode{Value: 2, Next: &link3}
link1 := LinkNode{Value: 1, Next: &link2}
//link5.Next=&link1 // 循环链表
print(link1.Value)
pre := reverse(&link1)
print(pre.Value)
}
//reverse 可以训练,长期练习
func reverse(current *LinkNode) *LinkNode {
var pre = &LinkNode{}
var next = &LinkNode{}
for current != nil {
next = current.Next
current.Next = pre
pre = current
current = next
}
return pre
}