Reverse a singly linked list.
思路:链表中节点 1-->2-->3-->4-->5-->6...-->n
将节点设置为prev-->head-->next
让head指向prev: prev<--head-->next
而后将prev与head平移: prev<--prev(new)<--head(原先的next位置)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
while(head != null){
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}