今年秋招第一次面试,小米后端研发问了这个问题,当时真的是脑袋晕啊,一点面试技巧都不懂...
以自己的实力,这种题目轻轻松松撕了...
维护三个指针左、中、右,边向后移动,边改变指针指向的方向。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode l = head, m = head.next, r; // 左节点、中节点、右节点
head.next = null;
while (m != null) {
r = m.next;
m.next = l;
l = m;
m = r;
}
return l;
}
}
京公网安备 11010502036488号