以下是Leetcode上一些關於鏈表的基本題目:
Leetcode#206:反轉鏈表
題目描述
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
算法思路
倒轉=將結點依次頭插到另一個鏈表中
代碼實現
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* p = NULL;
while( head != NULL){
swap(p, head->next);
swap(head, p);
}
return p;
}
};
執行用時:4ms , 內存消耗:10.2MB
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* p = NULL;
while( head ){
ListNode* t = p;
p = head;
head = head->next;
p->next = t;
}
return p;
}
};
執行用時:12ms , 內存消耗:10.2MB