链表
思路:
两个指针,pre
和 cur
, 遍历的时候 翻转指针
注意:
返回值应是 pre
因为 pre
指向了反转后链表的倒数第二个元素,也就是真实的头结点。
cur
此时为 null
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return null;
ListNode temp = null, pre = null, cur = head;
while (cur != null) {
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}