反转链表

题目 反转链表

image-5cd50699

思路分析

迭代写法

节点的先后顺序完全由next指针确定 要反转 那就把每个节点的next指向prev

头节点没有prev 所以初始化为空

递归写法

首先我们先考虑 reverseList 函数能做什么,它可以翻转一个链表,并返回新链表的头节点,也就是原链表的尾节点。

所以我们可以先递归处理 reverseList(head->next),这样我们可以将以head->next为头节点的链表翻转,并得到原链表的尾节点tail,此时head->next是新链表的尾节点,我们令它的next指针指向head,并将head->next指向空即可将整个链表翻转,且新链表的头节点是tail。

代码实现

迭代:

 /**
 * 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 prev=null;
        ListNode cur=head;
        while(cur!=null){
            ListNode realnext=cur.next;
            cur.next=prev;
            prev=cur;
            cur=realnext;
        }
        return prev;
    }
}

递归:

/**
 * 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 tail=reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return tail;
    }
}

同类题型

视频讲解


项目分区导航删除链表中重复的节点 ⬅️ | 04-反转链表 | ➡️ 在O(1)时间删除链表结点