您的位置:首页 > 其它

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: