首页 > 其他 > 详细

使用单链表逆置字符串

时间:2019-11-01 18:28:47      阅读:95      评论:0      收藏:0      [点我收藏+]

 

package org.codewy.algorithm.reverselinkedlist;

public class Node {

    private String val;

    private Node next;

    public Node(String data){
        this.val  = data;
    }

    public String getData() {
        return val;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "Node{" +
                "val=‘" + val + ‘\‘‘ +
                ‘}‘;
    }

}

方法一:

package org.codewy.algorithm.reverselinkedlist;

public class ReverseLinkedList {

    public static Node reverse(Node node) {
        Node prev = null;
        Node current = node;
        Node next = node.getNext();

        while (next != null) {
            //反转指针
            current.setNext(prev);
            prev = current;
            current = next;
            next = next.getNext();
        }

        current.setNext(prev);

        return current;
    }


    public static void main(String[] args) {
        Node a = new Node("a");
        Node b = new Node("b");
        Node c = new Node("c");
        Node d = new Node("d");
        Node e = new Node("e");
        a.setNext(b);
        b.setNext(c);
        c.setNext(d);
        d.setNext(e);
        Node result = reverse(a);
        while (result != null) {
            System.out.println(result);
            result = result.getNext();
        }
    }
}

输出结果:

技术分享图片

 

参考博客:

  https://blog.csdn.net/shengqianfeng/article/details/99677755

使用单链表逆置字符串

原文:https://www.cnblogs.com/codewy/p/11778548.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!