反转链表的意思是原来的链表顺序逆向存储。原来的头节点变成节点。原来的尾节点变成头节点。中间节点一次变换。
思路:
迭代赋值法:需要定义三个链表,一个指向空命名为pre还有一个代替需要改变的链表命名为cur最后一个指向cur.next命名为next.
依次迭代cur的每一个节点.先用next接管cur.next然后让cu.next指向pre.让pre指向cur.最后cur指向next.直到cur指向空为止.
代码:
public ListNode reverseList(ListNode head) {
ListNode pre = null, cur = head, next = null;
while(cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}