LeetCode:206. Reverse Linked List(單鏈表進行反轉)
阿新 • • 發佈:2018-11-23
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
解法一(非遞迴方式):
public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } return prev;
時間複雜度:O(n)
空間複雜度:O(1)
解法二(遞迴的方式):
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
時間複雜度:O(n)
空間複雜度:O(n) ---遞迴需要額外的空間
利用C語言進行連結串列的反轉:
1.利用非遞迴式:
Node* reverseList(Node* head){ if(head==null||head->next==null){ return head; } Node * p=head; Node* newp=null; while(p!=null){ Node* temp=p->next; //儲存一個臨時位置 p->next=newp; // 將p的next域指向空 newp=p; // 新的指標指向 p=temp; // p指向下一個元素 } return newp; }
時間複雜度和空間複雜度同上
2.利用遞迴方式:
Node * reverseList(Node* head){
if(head==null || head->next==null){ //如果它為空或者只有一個元素 ,就不變
return head;
}
Node* newHead=reverseList(head->next);
head->next->next=head; //指正反過來指向
head->next=null; // 將自己指向空,防止出現異常
return newHead; // 返回最後newHead指標
}
時間複雜度和空間複雜度同上;