LeetCode 206 链表 Reverse Linked List
Posted Muche
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 206 链表 Reverse Linked List相关的知识,希望对你有一定的参考价值。
LeetCode 206 链表 Reverse Linked List
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
代码:
iteratively
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null) return null;
ListNode newNode = null;
ListNode oldNode = head;
while(oldNode != null){
ListNode tmp = oldNode.next;
oldNode.next = newNode;
newNode = oldNode;
oldNode = tmp;
}
return newNode;
}
}
recursively
public ListNode reverseList(ListNode head) {
return reverse(null,head);
}
private static ListNode reverse(ListNode pre,ListNode cur){
if(cur==null) return pre;
ListNode next = cur.next;
cur.next = pre;
return reverse(cur,next);
}
注意:
不要创建新节点
以上是关于LeetCode 206 链表 Reverse Linked List的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 206 Reverse Linked List 链表
(Java) LeetCode 206. Reverse Linked List —— 反转链表
leetcode 206. 反转链表(Reverse Linked List)