链接:https://leetcode-cn.com/problems/reverse-linked-list/
思路一:
递归实现
请读者深入理解该函数的意义 0_0
public ListNode reverseList(ListNode head)
返回以当前节点下一跳为头节点的链表经过反转后的头节点
例如:ListNode h=reverseList(head.next)
解释:head当前节点,head.next当前节点下一跳,h反转后链表的头结点
好了,看代码吧
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.next = null;
return h;
}
}
思路二:
新建节点,头插法
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode root=new ListNode(0);
ListNode n=root;
while(head!=null){
n=head;
head=head.next;
n.next=null;
n.next=root.next;
root.next=n;
}
return root.next;
}
}