彻底弄懂反转链表(递归和迭代)

真的是脑子不好使

每次弄懂下次再看就迷糊了

如果有和我一样蠢得可以举一个简单地例子来逐步实现代码 理清什么套路,就像我迭代那样哈哈哈

递归:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode headNode = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return headNode;
    }
}

关键代码解释:
 

head.next.next = head
head.next 最后一个节点
head 倒数第二个节点
表示最后一个节点指向倒数第二个节点

迭代:

ListNode newList = new ListNode(-1);
while(head != null){
    ListNode next = head.next;
    head.next = newList.next;
    newList.next = head;
    head = next;

}
return newList.next;

哈哈哈

 

猜你喜欢

转载自blog.csdn.net/ailaojie/article/details/85242942