206. Reverse Linked List(Java)
1176 ワード
注意:このブログは更新されません.すべての最新記事は個人独立ブログlimengtingに発表されます.site.技術を共有し、生活を記録し、注目を集めてください.
Reverse a singly linked list.
A linked list can be reversed either iteratively or recursively. Could you implement both?
コード1:recursive solution
コード2:iterative solution
Reverse a singly linked list.
A linked list can be reversed either iteratively or recursively. Could you implement both?
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
コード1:recursive solution
public class Solution {
public ListNode reverseList(ListNode head) {
return reverseListInt(head, null);
}
private ListNode reverseListInt(ListNode head, ListNode newNext) {
if (head == null)
return newNext;
ListNode oldNext = head.next;
head.next = newNext;
return reverseListInt(oldNext, head);
}
}
コード2:iterative solution
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode newNext = null;
while (head != null) {
ListNode oldNext = head.next;
head.next = newNext;
newNext = head;
head = oldNext;
}
return newNext;
}
}