标签:code 测试 tno down val reverse 分析 linked 转移
Reverse a singly linked list.
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
题目归类:
题目分析:
测试用例构建
非递归
/**
* 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;
while(head != null){
ListNode tmp = head.next;
head.next = prev;
prev = head;
head = tmp;
}
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 tmp = reverseList(head.next);
head.next.next = head;
head.next = null;
return tmp;
}
}
Reverse Linked List II
Medium
Binary Tree Upside Down
Medium
Palindrome Linked List
Easy
leetcode 206. Reverse Linked List
标签:code 测试 tno down val reverse 分析 linked 转移
原文地址:https://www.cnblogs.com/clnsx/p/12307742.html