2021-04-25 链表反转

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
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 混沌愚昧何其长, 电光火石破天窗。 仓颉造字霹雳出, 华夏文明万古扬。
    南风天一阅读 428评论 2 10
  • 有的时候,趁晚风微凉的时候,我总是想留住些什么,留住和恋人一起走过的夕阳,留住美妙的花房。 我喜欢满满当当的日子,...
    Crush大橘阅读 109评论 0 0
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,617评论 0 11
  • 彩排完,天已黑
    刘凯书法阅读 4,281评论 1 3
  • 表情是什么,我认为表情就是表现出来的情绪。表情可以传达很多信息。高兴了当然就笑了,难过就哭了。两者是相互影响密不可...
    Persistenc_6aea阅读 126,151评论 2 7