题目:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/6/linked-list/43/
题目描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
思路:第一种解法: 1-->2 -->3 -->4--> 5
2-->1 -->3 -->4--> 5
3--> 2-->1 -->4--> 5 ...... 就是操作起来很好难想
第二种 :2-->1 -->3 -->4--> 5 2-->3 -->1 -->4--> 5 2-->3 -->4-->1 --> 5 2-->3 -->4--> 5 -->1
以此类推。把全都移动一遍。实现起来也比较难想。头晕。
//迭代法。
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null||head.next == null){
return head;
}
ListNode curr = head;
ListNode pre = null;
ListNode next = null;
ListNode head_node = head;
while(curr!=null){
next = curr.next;
if(next == null){
head_node = curr;
}
curr.next = pre;
pre = curr;
curr = next;
}
return head_node;
}
}
//递归
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null){/*递归的终止条件,返回的尾结点*/
return head;
}
else{
ListNode p = head.next;//a
ListNode rehead = reverseList(p);//b
p.next = head;//c
head.next=null;//d
return rehead;
}
}
}