剑指offer_编程题_翻转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

分析

当前节点是head,pre为当前节点的前一节点,next为当前节点的下一节点.
需要pre和next的目的是让当前节点从pre->head->next1->next2变成pre<-head next1->next2即pre让节点可以反转所指方向,但反转之后如果不用next节点保存next1节点的话,此单链表就此断开了所以需要用到pre和next两个节点.
具体操作:

 next = head.next;    //先保存当前节点的下一个节点
 head.next = pre;     //  当前节点指向pre
 pre = head;            //当前节点赋值给pre,即当前节点前移一位
 head = next;           //原当前节点的下一个节点赋值给当前节点,即下一节点前移一位

源代码

public class Dome5_plus {
    int data;
    Dome5_plus next=null;
    Dome5_plus(int data){
        this.data=data;
    }


    public static void main(String[] args) {
        Dome5_plus head=new Dome5_plus(0);
        Dome5_plus head1=new Dome5_plus(1);
        Dome5_plus head2=new Dome5_plus(2);
        Dome5_plus head3=new Dome5_plus(3);
        head.data=0;
        head.next=head1;
        head1.next=head2;
        head2.next=head3;
        System.out.println(head.data+"->"+head1.data+"->"+head2.data+"->"+head3.data);
        head=head.ReverseList(head);
        System.out.println(head.data+"->"+head1.data+"->"+head2.data+"->"+head3.data);
    }

    /**
     *
     * @param head  目标头节点
     * @return   翻转后的头结点
     */
    public Dome5_plus ReverseList(Dome5_plus head) {
        Dome5_plus pre = null;
        Dome5_plus next = null;
        if (head == null) {//如果节点为空的话,就返回null
            return null;
        }
        while (head != null) {
            //先保存当前节点的下一个节点
            next = head.next;
            //当前节点指向pre
            head.next = pre;
            //当前节点赋值给pre,即当前节点前移一位
            pre = head;
            //原当前节点的下一个节点赋值给当前节点,即下一节点前移一位
            head = next;
        }
        return pre;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值