反转链表Java实现

package cn.wangss.demo;

/**
 * 反转链表
 * @author LiPeng
 *
 */
public class Test {
    public static Node Reverse(Node head){
        Node current=head;
        Node nextTemp=null;
        Node prevTemp=null;
        while(current!=null){
            //保存当前节点的next引用到临时变量nextTemp,防止下一步更新当前节点的next引用
            //为上一个节点时丢失未反转之前的next节点的引用。
            nextTemp=current.getNext();
            //将当前节点的next引用设置成上一个节点
            current.setNext(prevTemp);
            //更新prevTemp引用为当前节点
            prevTemp=current;
            //更新current引用为nextTemp,开始下一次循环
            current=nextTemp;
        }
        return head;
    } 

    public static void main(String[] args) {
        Node node3=new Node("3", null);
        Node node2=new Node("2", node3);
        Node node1=new Node("1", node2);
        //传入首节点 反转
        Test.Reverse(node1);
        Node current=node3;
        while(current!=null){
            System.out.println(current.getId());
            current=current.getNext();
        }
    }


    static class Node{
        private String id;
        private Node next;
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public Node getNext() {
            return next;
        }
        public void setNext(Node next) {
            this.next = next;
        }
        public Node(String id, Node next) {
            super();
            this.id = id;
            this.next = next;
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值