链表反转

迭代法
思想:一边是新链表,一边是原链表。不断地将原链表的头节点头插到新链表中。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode list = head;
        ListNode newList = null;
        ListNode current = null;
        while (list != null) {
        	//保存下一个节点
            current = list.next;
            //处理当前头节点,将其头插到新链表
            list.next = newList;
            newList = list;
           
            list = current;
        }
        return newList;
    }
}

递归法

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode sublist = reverseList(head.next);
        
        if (sublist == null)
            return head;
        ListNode current = sublist;
        while (current.next != null) {
            current = current.next;
        }
        head.next = current.next;
        current.next = head;
        return sublist;
    }
}

看到更简单的递归

    public ListNode reverseList(ListNode head) {
        /* recursive solution */
        return reverseListInt(head, null);
    }
    
    private ListNode reverseListInt(ListNode head, ListNode newHead) {
        if (head == null)
            return newHead;
            //保存下一个要处理的结点
        ListNode next = head.next;
        //在原链表处理头结点
        head.next = newHead;
        //处理下一个结点
        return reverseListInt(next, head);
    }
   
感觉迭代的方法更容易实现。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值