标签:ever end == html sans ble fun data 链表
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
标签:ever end == html sans ble fun data 链表
原文地址:https://www.cnblogs.com/muche-moqi/p/12393036.html