Skip to content

Latest commit

 

History

History

3.3 Reverse Linked List

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Reverse Linked List(反转链表)

From

LeetCode 206

Question

Reverse a singly linked list.

input: 1->2->3->4->5->NULL
output: 5->4->3->2->1->NULL

Solution

C++

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* reverseList(ListNode *head){

        ListNode *preNode = NULL;
        ListNode *curNode = head;

        while ( curNode != NULL){

            ListNode *nextNode = curNode->next;
           
            //change pointer direction
            curNode->next = preNode;
            preNode = curNode;
            curNode = nextNode;
        }

        //pre will be the first node after reversing
        return preNode;
    }
};

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 preNode = null;
        ListNode curNode = head;
        
        while ( curNode != null ){
            
            ListNode nextNode = curNode.next;
            
            curNode.next = preNode;
            preNode = curNode;
            curNode = nextNode;
        }
        
        return preNode;
    }
}