反转一个单链表。
进阶:
链表可以迭代或递归地反转。你能否两个都实现一遍?
思路:
https://blog.csdn.net/fx677588/article/details/72357389
1. 首先是迭代的反转链表
方式如上图所示,
2. 利用递归
代码:
/**
* 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 pre = null;
// ListNode next = null;
// while(head!=null){
// next = head.next;
// head.next = pre;
// pre = head;
// head = next;
// }
// return pre;
if(head==null || head.next==null){
return head;
}
ListNode h = reverseList(head.next);
head.next.next = head;
head.next = null;
return h;
}
}