您好,登錄后才能下訂單哦!
從尾到頭打印單鏈表
void FromTailToHeadPrint(SListNode*& head) { stack<SListNode*> s; SListNode* cur = head; while (cur) { s.push(cur); cur = cur->_next; } while (!s.empty()) { cout << s.top()->_data <<"->"; s.pop(); } cout << ""<<endl; }
2.刪除一個無頭單鏈表的非尾節(jié)點
void Erase(SListNode*& head,SListNode* pos) { //分情況:空節(jié)點、一個節(jié)點、兩個節(jié)點、三個節(jié)點 if (head == NULL || pos==NULL) { return; } if (head == pos) { free(head); head = NULL; return; } SListNode* cur = head; while (cur) { SListNode* next = cur->_next; if (next == pos) { //若只有兩個節(jié)點,pos=next,nextnext=NULL,cur->_next = nextnext; //(即使題設(shè)未說明刪除非尾節(jié)點)依然可以刪除成功。 SListNode* nextnext = next->_next; cur->_next = nextnext; free(next); next = NULL; } cur = cur->_next; } }
3.逆置、反轉(zhuǎn)單鏈表
void Reverse(SListNode*& head) { if (head == NULL) { return; } SListNode* cur = head; SListNode* next = NULL; while (cur) { SListNode* tmp = cur; cur = cur->_next; tmp->_next = next; next = tmp; head = tmp; } }
4.單鏈表冒泡排序
void BubbleSort(SListNode*& head) { //空節(jié)點或一個節(jié)點直接返回 if (head == NULL || head->_next == NULL) { return; } SListNode* begin = head; SListNode* cur = head; while (begin->_next) { while (cur->_next) { if (cur->_data > cur->_next->_data) { swap(cur->_data, cur->_next->_data); } cur = cur->_next; } begin = begin->_next; } }
5.查找單鏈表的中間節(jié)點,要求只能遍歷一次鏈表
SListNode* FindMiddle(SListNode*& head) { if (head == NULL) { return NULL; } SListNode* slow = head; SListNode* fast = head; while (fast->_next) { if (fast->_next) { fast = fast->_next; if (fast->_next) { fast = fast->_next; } else { return slow; } slow = slow->_next; } else { return NULL; } } return slow; }
6.查找單鏈表的倒數(shù)第k個節(jié)點,要求只能遍歷一次鏈表
SListNode* FindLastK(SListNode*& head,int k) { assert(k > 0); if (head == NULL) { return NULL; } SListNode* slow = head; SListNode* fast = head; while (k--) { if (fast->_next) { fast = fast->_next; } else { return NULL; } } slow = slow->_next; while (fast->_next) { fast = fast->_next; slow = slow->_next; } return slow; }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。