Reverse a singly linked list.
Subscribe to see which companies asked this question
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null) return head;
ListNode fis = head;
ListNode sed = head.next;
fis.next = null;
while(sed != null){
ListNode thd = sed.next;
sed.next = fis;
fis = sed;
sed = thd;
}
return fis;
}
}
总结:看到本题目,我首先想到了,运用List,循环把ListNode都添加到List里面,在逆序插入到一个数组,但是结果内存超时限制了,在Eclipse上亲测可用,本题解法代码,也是有参考到别人的代码,ListNode算是我的一个弱项,主要是太绕了。下面图片都本代码的思路,仅供参考。