这是一道道简单的链表题,但是有很多大公司都有出这道面试题,可见基础题在面试中也很重要
这里有两种解法,虽然大体相同,但是耗时不同
Reverse a singly linked list.
第一种解法
/**
* 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)
return head;
ListNode cur = head;
ListNode pre = null;
ListNode Next = cur.next;//如果在while之外定义的话会出现head = null时异常
while(cur != null)
{
cur.next = pre;
pre = cur;
cur = Next;
if(cur != null)
Next = cur.next;
}
return pre;
}
}
第二种解法
/**
* 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)
return head;
ListNode cur = head;
ListNode pre = null;
ListNode Next = cur.next;//如果在while之外定义的话会出现head = null时异常
while(cur != null)
{
cur.next = pre;
pre = cur;
cur = Next;
if(cur != null)
Next = cur.next;
}
return pre;
}
}