牛客网高频算法题系列-BM1 反转链表
题目形容
给定一个单链表的头结点pHead(该头节点是有值的),长度为n,反转该链表后,返回新链表的表头。
原题目见:BM1 反转链表
解法一:结点反转
- 首先,如果head为空或者只有一个结点,间接返回。
- 否则,别离用first和next指针指向链表的前两个结点,并将它们的next指针域反转,而后持续往后遍历解决链表的后续结点直到将最初一个结点反转。留神,须要将head头结点的next指向null。
- 最初,返回first结点,即为反转后的新链表的头结点。
解法二:递归法
- 同样的,首先须要判断,如果head为空或者只有一个结点,间接返回。
否则,通过递归的形式来解决,递归的解决流程如下:
- 递归的终结条件是head结点为空或者没有下一个结点;
- 否则,递归失去
head.next
的反转链表为reverse,而后将reverse的next指针指向head,同样要记住须要将head头结点的next指向null。
public class Bm001 { /** * 反转结点 * * @param head 原链表的头结点 * @return */ public static ListNode reverseList(ListNode head) { // 如果链表为空或者只有一个节点,不须要反转,间接返回原链表 if (head == null || head.next == null) { return head; } ListNode first = head, second = head.next; first.next = null; while (first != null && second != null) { ListNode temp = first; first = second; second = second.next; first.next = temp; } return first; } /** * 递归法 * * @param head 原链表的头结点 * @return */ public static ListNode reverseList2(ListNode head) { // 递归的终止条件 if (head == null || head.next == null) { return head; } // 递归解决 ListNode reverse = reverseList2(head.next); head.next.next = head; head.next = null; return reverse; } public static void main(String[] args) { // 测试用例 ListNode head = ListNode.testCase1(); System.out.println("反转之前"); ListNode.print(head); System.out.println("反转之后"); ListNode newHead = reverseList(head); ListNode.print(newHead); System.out.println("再次反转之后"); ListNode newHead2 = reverseList2(newHead); ListNode.print(newHead2); }}
$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
置信保持的力量!