206. 反转链表
](https://leetcode.cn/problems/reverse-linked-list/description/)
思路
1、头插法
2、迭代法
3、递归
Code1
//使用虚拟节点 头插法
class Solution_2 {
public ListNode reverseList(ListNode head) {
if (head == null) {
return head;
}
ListNode newhead = new ListNode(0);
ListNode cur = head;
ListNode prev = newhead;
while (cur != null) {
ListNode t = cur;
cur = cur.next;
t.next = prev.next;
prev.next = t;
}
return newhead.next;
}
}
Code2
class Solution_1 {
public ListNode reverseList(ListNode head) {
if (head == null) {
return head;
}
// ListNode newhead = new ListNode(0);
ListNode newhead= null;
ListNode prev = head;
while (head != null) {
prev = head;
head = head.next;
prev.next = newhead;
newhead = prev;
}
return newhead;
}
}
Code3
class Solution_1 {
public ListNode reverseList(ListNode head) {
if (head == null) {
return head;
}
// ListNode newhead = new ListNode(0);
ListNode newhead= null;
ListNode prev = head;
while (head != null) {
prev = head;
head = head.next;
prev.next = newhead;
newhead = prev;
}
return newhead;
}
}