78. Reverse Linked List

Title description

Input a linked list, after inverting the linked list, output the header of the new linked list.

Example 1

enter

{1,2,3}

return value

{3,2,1}
Code implementation :
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
}

 

Guess you like

Origin blog.csdn.net/xiao__jia__jia/article/details/113478905