본문 바로가기

Amazon/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?


<SOLVE>

.java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode cur  = head;
        ListNode next = null;
       
        while(cur != null){
            next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
}


.py


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prev = None
        cur = head
        next = None
       
        while(cur != None):
            next = cur.next
            cur.next = prev
            prev = cur
            cur = next
       
        return prev
       

'Amazon > Leetcode' 카테고리의 다른 글

819. Most Common Word  (0) 2018.08.01
235. Lowest Common Ancestor of a Binary Search Tree  (0) 2018.07.31
5. Longest Palindromic Substring  (0) 2018.07.29
535. Encode and Decode TinyURL  (0) 2018.07.29
617. Merge Two Binary Trees  (0) 2018.07.27