给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
public ListNode reverseList(ListNode head){
/**
* 方法一:头插法(遍历原链表,头插到新链表中)
*/
if(head == null || head.next == null){
return head;
}
ListNode newHead = null;
while(head != null){
ListNode node = new ListNode(head.val);
//新的头结点,就是原来链表中node的下一个节点
//将node与newHead连接起来
node.next = newHead;
//newHead指向node,即2指向1,3指向2 ……
newHead = node;
head = head.next;
}
return newHead;
}
/**
* 原地移动原链表法
*/
public ListNode reverseList(ListNode head){
if(head == null || head.next == null){
return head;
}
//prev是头结点的前一个节点
ListNode prev = null;
//cur是头结点
ListNode cur = head;
while(cur != null){
//next是头结点的下一个节点
ListNode next = cur.next;
//cur指向prev,即头结点1指向null,2指向1 ……
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
/**
* 递归法(传入一个链表,将此链表进行翻转,并返回翻转后的链表头结点)
*/
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
//将链表分为两部分,头和头之后的部分
ListNode secNode = head.next;
//新建一个链表,存放翻转后的链表,这部分递归
ListNode newHead = reverseList(head.next);
//第二部分指向第一部分,即头结点指向null,第二部分指向第一部分 ……
secNode.next = head;
head.next = null;
return newHead;
}