Java面试系列-算法-反转链表

198 阅读1分钟

题目

如题,反转单链表。

给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。

如当输入链表{1,2,3}时,

经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。

以上转换过程如下图所示:

image.png

方法

迭代

思路

将当前节点的next指向前一节点,最终之前的head节点应该指向null,尾部节点变为头节点。 1.遍历链表 2.从头开始遍历 - cur = head 3.当遍历到 cur = null时终止,如下图 4.声明未来的头结点(pre),一直跟随cur后移

image.png

/**
 * 反转链表
 * 头变尾 尾变头
 * 最后的尾部为null
 *
 * 1->2->3->4->5
 *
 * 1<-2<-3<-4<-5
 *
 * 返回 5
 *
 * @param head
 * @return
 */
public ListNode ReverseListNode(ListNode head) {
    if (head == null || head.next == null) return null;
    ListNode pre = null;
    ListNode cur = head;
    while (cur != null) {
        ListNode curNext = cur.next;
        cur.next = pre;
        pre = cur;
        cur = curNext;
    }
    return pre;
}

递归

如图解

image.png

public ListNode ReverseListNode(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }
    ListNode pre = ReverseListDiGui(head.next);
    head.next.next = head;
    head.next = null;
    
    return pre;
}