目录
https://leetcode.com/problems/reverse-linked-list/
反转单链表
一、问题分析
测试用例:
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
要求同时实现迭代版本和递归版本
二、代码实现
1、迭代版本
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList2(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = null, cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
public ListNode reverseList1(ListNode head) {
if (head == null || head.next == null) {
return head;
}
//head.length >= 2
ListNode tempHead = head;
head = head.next;
tempHead.next = null;
//tempHead and head are two lists that are not interacted
while (head != null) {
ListNode temp = head;
head = head.next;
temp.next = tempHead;
tempHead = temp;
}
return tempHead;
}
}
2、递归版本
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList3(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next); //将除了头节点之外的部分反转完,返回反转后的新头节点
//此时 head-> newTail(head.next) <-> ... <- newHead
head.next.next = head;
head.next = null;
return newHead;
}
}
参考: