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;
}
}