题目描述
反转链表
思路
和leetcode的206. Reverse Linked List一样
迭代:
- 记录当前结点的下一个结点
- 反转指针
- 继续下一个结点
- 返回反转后的头结点
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null) return null;
// 反转后的头结点
ListNode newHead = null;
while (head != null) {
// 记录当前结点的下一个结点
ListNode next_node = head.next;
// 反转指针
head.next = newHead;
newHead = head;
// 继续下一个结点
head = next_node;
}
return newHead;
}
}
递归:
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode head_next = head.next;
head.next = null;
ListNode newHead = ReverseList(head_next);
head_next.next = head;
return newHead;
}
}