标签:turn http null pac tco lis head link ack
package 链表;
/**
* https://leetcode-cn.com/problems/reverse-linked-list/
* 206. 反转链表
*
* 解题思路 :使用给定节点的后一个节点的值覆盖给定节点的值,然后删除下一个节点
*/
public class _206_Reverse_Linked_List {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
/**
* 迭代
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = null;
while (head != null) {
ListNode tmp = head.next;
head.next = newHead;
newHead = head;
head = tmp;
}
return newHead;
}
}
/**
* 递归
*
* @param head
* @return
*/
public ListNode reverseList(ListNode head) {
// head == null 一定要写在head.next前面
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
标签:turn http null pac tco lis head link ack
原文地址:https://www.cnblogs.com/jianzha/p/12810591.html