/**
* 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 cur = head;
ListNode q = null;
ListNode pre;
while(cur != null){
pre = cur.next;
cur.next = q;
q = cur;
cur = pre;
}
return q;
}
}
核心思想:
a.创建一个新的节点q,用来存放反转后的链表,当前节点为cur
b.保存当前节点的下一个节点,并且使当前节点cur的引用指向新的节点q;
c.q开始接上了节点,并且是该链表不断向前,用末尾来接收,因此q = cur;
d.使cur = pre,这里特别留意,由于cur.next已经改变,所以要使用原来存的pre。