Java [Leetcode 206]Reverse Linked List

时间:2021-12-28 03:31:41

题目描述:

Reverse a singly linked list.

解题思路:

使用递归或者迭代的方法。

代码如下:

方法一:递归

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

方法二:迭代

public ListNode reverseList(ListNode head) { // iteratively
ListNode nextNode = null;
while(head != null){
ListNode next = head.next;
head.next = nextNode;
nextNode = head;
head = next;
}
return nextNode;
}