题目
Leetcode206题
给你单链表的头节点 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.next = newHead;
newHead = node;
head = head.next;
}
return newHead;
}
方法二:递归法
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// 此时第二个节点以及之后节点的反转工作交给reverseList()执行,并且,返回的链表头就是最终的返回值
ListNode secNode = head.next;
ListNode newHead = reverseList(head.next);
secNode.next = head;
head.next = null;
return newHead;
}
方法三:原地移动原链表
实际上就是将相邻的两个节点互换,因此需要两个遥控器指向两节点
// 2.原地移动原链表
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode prev = null;
ListNode cur = head;
while (cur != null) {
// 使用next暂存下一个 要处理的节点
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}