反转流程演示
并不需要真正去交换每个节点的位置,只需要更改指针的方向即可。
代码实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode q = head.next, p = head;
head.next = null;
while(q != null) {
ListNode tmp = q.next;
q.next = p;
p = q;
q = tmp;
}
return p;
}
}
击败双百,bingo~