Reverse a Singly LinkedList

时间:2023-03-08 21:54:34
Reverse a Singly LinkedList
 * Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/

这是面试的时候被问到的一题,还是考察LinkedList的理解,最后如何得到reverse之后的head的。

public Class Solution{

    public static ListNode reverseList(ListNode head){
if(head == null || head.next == null){
return head;
} ListNode next = head.next;
head.next = null;
while(next != null){
ListNode temp = next.next;
next.next = head;
head = next;
next = temp;
} return head;
}
}