206、反转链表(链表)

题意:反转一个单链表。

示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL

方法一:双指针法

public class Fanzhuanlianbiao {
    static class ListNode{
        int val;//数据:节点数据
        ListNode next;//对象,引用下一个数据对象

        //链表类的构造方法
        ListNode(int val){
            this.val = val;
        }
    }
    public void print (ListNode head){
        while(head!=null){
            System.out.print(head.val+" ");
            head = head.next;
        }
    }
    public ListNode reverseList(ListNode head){
        //定义一个临时变量保存当前节点的下一个节点
        ListNode temp;
        //定义前驱节点
        ListNode pre = null;
        //定义当前节点
        ListNode cur = head;
        while(cur!=null){
            //临时变量记录当前节点的下一个节点
            temp=cur.next;
            //当前节点指向前驱结点
            cur.next = pre;
            //前驱结点后移一位
            pre = cur;
            //当前节点后移一位
            cur = temp;
        }
        return pre;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        Fanzhuanlianbiao fanzhuanlianbiao = new Fanzhuanlianbiao();
        ListNode node = node1;
        fanzhuanlianbiao.print(node);
        System.out.println();

        ListNode res =fanzhuanlianbiao.reverseList(node1);
        fanzhuanlianbiao.print(res);
    }
}

输出结果:

12345

54321 

方法二:递归法

思路跟双指针类似,注意递归的终点和递归的变量

//递归法
    public ListNode reverseList(ListNode head){
        return reverse(null,head);
    }
    private ListNode reverse(ListNode pre,ListNode cur){
        //到达递归终点,返回pre
        if (cur==null){
            return pre;
        }
        //定义临时节点temp保存当前节点下一个节点
        ListNode temp = null;
        temp = cur.next;
        //反转(当前节点指向前一个节点
        cur.next = pre;
        return reverse(cur,temp);
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值