206. 反轉(zhuǎn)一個(gè)單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode loopNode = head;
ListNode reverseNode = null;
while (loopNode != null) {
ListNode temp = loopNode.next;
loopNode.next = reverseNode;
reverseNode = loopNode;
loopNode = temp;
}
return reverseNode;
}
}
復(fù)雜度分析
時(shí)間復(fù)雜度 : O(n)
空間復(fù)雜度 : O(1)