算法通关村第二关--终于学会链表反转了(Java)

1.建立虚拟节点辅助反转

第一次循环:

ListNode ans = new ListNode(-1);//创建虚拟头节点,简化代码
ListNode cur = head;//将传入的链表赋给cur
ListNode next = cur.next;//next即还未处理的链表

cur.next = ans.next;//第一次循环的时候,ans.next = null

ans.next = cur;

cur = next;

第二次循环:

ListNode next = cur.next;

cur.next = ans.next;//第二次循环的时候ans.next = 4

ans.next = cur;

cur = next;

…依次循环,当cur为空时,返回ans链表,即为反转之后的链表

下面为完整代码:

public static ListNode reverseListByDummyNotCreate(ListNode head) {
    ListNode ans = new ListNode(-1);
    ListNode cur = head;
    while (cur != null) {
        ListNode next = cur.next;
        cur.next = ans.next;
        ans.next = cur;
        cur = next;
    }
    return ans.next;
}

2.直接操作链表进行反转

与创建虚拟节点相比,直接操作链表的方法是在开始的时候创建prev指针代替虚拟节点

在代码的体现上ans.next = prev;

public static ListNode reverseListSimple(ListNode head) {
    ListNode prev = null;
    ListNode curr = head;
    while (curr != null) {
        ListNode next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}

 3.利用递归进行反转(拓展)

递归:

1. 函数要实现的功能->反转链表

 public static ListNode reverseListByRecurse(ListNode head) {
      
 }

2. 递归的循环结束条件->当链表为空表或者只有一个节点返回head

public static ListNode reverseListByRecurse(ListNode head) {
     if (head == null || head.next == null) {
           return head;
     }
}

3. 函数的等价关系式->将子链表先反转

ListNode newHead = reverseListByRecurse(head.next);

   这个时候head为4->3

   head.next.next = head;

   head.next.next = head变成4->3->4->3->4->3……

 head.next = null;

  

   完整代码如下:

public static ListNode reverseListByRecurse(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }
    ListNode newHead = reverseListByRecurse(head.next);
    head.next.next = head;
    head.next = null;
    return newHead;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值