反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
方法1、递归思想(代码简单但比较难理解)
难点:
递归要层层调用,将下一级的返回结果传给上一级;结合图容易理解
图解
代码实现
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode h=reverseList(head.next); //递归调用
head.next.next=head; //将上一级的结点(head)放在下一级结点(head.next)的后面
head.next=null; //将上一级结点之后置空
return h; //返回一个链表
}
}
方法2、迭代思想(代码复杂但容易理解)
图解
**难点
n.next=root.next; //头插法,root结点后的所有元素接在n的后面
root.next=n; //将n接在root的下一个位置,n为链表的第一个元素
代码实现
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode root=new ListNode(0); //虚设一个root结点,root为一个借助工具
ListNode n=new ListNode(0); //给n赋予个初始值
while(head!=null){
n=head; //第一个元素赋给n
head=head.next; //head后移
n.next=null; //将n的下一个置空
n.next=root.next; //头插法,root结点后的所有元素接在n的后面
root.next=n; //将n接在root的下一个位置,n为链表的第一个元素
}
return root.next; //返回新链表的头节点
}
}