LeetCode 206 Reverse Linked List (逆置链表)
2016-08-29 20:11
405 查看
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
题目链接:https://leetcode.com/problems/reverse-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) {
if(head == null) {
return head;
}
ListNode cur = head.next;
head.next = null;
while(cur != null) {
ListNode tmp = cur.next;
cur.next = head;
head = cur;
cur = tmp;
}
return head;
}
}
递归法:所谓递归,就当有个栈在维护
/**
* 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) {
if(head == null || head.next == null) {
return head;
}
ListNode Rhead = reverseList(head.next);
head.next.next = head;
head.next = null;
return Rhead;
}
}
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
题目链接:https://leetcode.com/problems/reverse-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) {
if(head == null) {
return head;
}
ListNode cur = head.next;
head.next = null;
while(cur != null) {
ListNode tmp = cur.next;
cur.next = head;
head = cur;
cur = tmp;
}
return head;
}
}
递归法:所谓递归,就当有个栈在维护
/**
* 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) {
if(head == null || head.next == null) {
return head;
}
ListNode Rhead = reverseList(head.next);
head.next.next = head;
head.next = null;
return Rhead;
}
}
相关文章推荐
- scala反转链表 leetcode 206 Reverse Linked List
- LeetCode 206 Reverse Linked List(链表操作)
- 【leetcode】【单链表】【206】Reverse Linked List
- LeetCode206——Reverse Linked List 反转链表
- leetcode_206题——Reverse Linked List(链表)
- leetcode206/92---Reverse Linked List I/II(反转链表)
- leetcode解题之206 # Reverse Linked List Java版 (使用头插法反转链表)
- LeetCode 206 Reverse Linked List(反转链表)(四步将递归改写成迭代)(*)
- [LeetCode-206] Reverse Linked List(链表反转)
- 【leetcode】【单链表】【206】Reverse Linked List
- LeetCode 206 Reverse Linked List(反转链表)(Linked List)(四步将递归改写成迭代)(*)
- 剑指offer 面试题16:反转链表(Leetcode 206: Reverse Linked List) 题解
- leetcode206-Reverse Linked List-反转链表
- Leetcode:Reverse Linked List II 单链表区间范围内逆置
- Leetcode 206 Reverse Linked List 链表
- [LeetCode] Reverse Linked List 倒置链表
- 【leetcode】【单链表】【92】Reverse Linked List II
- LeetCode 206 - Reverse Linked List
- [Leetcode 206, Easy] Reverse Linked List
- [LeetCode] 翻转子链表 reverse linked list