鏈表-常見題
阿新 • • 發佈:2018-09-05
存儲 ret while 鏈表是否有環 empty node false truct stack
struct Node { int _data; Node *_next; };
逆序:
1)修改指向:效率較低
1 Node* reverseList(Node *head) { 2 if (head == 0) return head; 3 Node *p = head->_next; 4 if (p == 0) return head; 5 Node *q = head, *tmp; 6 while (p) { 7 tmp = p->_next; 8 p->_next = q;9 q = p; 10 p = tmp; 11 } 12 head->_next = 0; 13 return q; 14 }
2)棧存儲值,然後修改節點值
1 Node* reverseList2(Node *head) { 2 if (head == 0) return head; 3 Node *p = head; 4 stack<int> s; 5 while (p) { 6 s.push(p->_data); 7 p = p->_next;8 } 9 p = head; 10 while (!s.empty()) { 11 p->_data = s.top(); 12 p = p->_next; 13 s.pop(); 14 } 15 return head; 16 }
判斷鏈表是否有環:快慢指針
1 bool hasCycle(ListNode *head) { 2 if (head == nullptr) return false; 3 4 ListNode *fast, *slow; 5fast = slow = head; 6 7 do { 8 fast = fast->_next; 9 if (fast == nullptr) return false; 10 fast = fast->_next; 11 12 slow = slow->_next; 13 14 } while (fast && fast != slow); 15 16 if (fast == nullptr) return false; 17 return true; 18 }
約瑟夫問題:省略
鏈表-常見題