Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL 翻译过来就是反转链表。
定义两个节点
遍历链表,结束条件为当前节点不为null
返回 prev(遍历结束时,当前节点已为null,此时的链表的头节点应该为prev)
/**
* 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 current = head;
ListNode prev = null;
while(current != null) {
ListNode next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;}}