Print a single linked list from the end of the head
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. delete
Void erase (Slistnode*& head,slistnode* pos) { //: Empty node, one node, two nodes, Three nodes 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) &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp { //If there are only two nodes, pos=next,nextnext=null,cur- >_next = nextnext; // (Even if the problem set does not indicate that deleting the non-tail node) can still be deleted successfully. SListNode* nextnext = next->_next; cur->_next = nextnext; free (Next); next = NULL; } cur = cur->_next; }}
3. Reverse and reverse a single linked list
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; }}
Void bubblesort (slistnode*& head) { //empty node or a node returns directly 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. find the middle node of a single linked list, which requires only one link list to be traversed
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. find the reciprocal k node of a single linked list, which requires only one link list to traverse once
SLISTNODE*&NBSP;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;}
This article is from "Han Jing's Blog", please make sure to keep this source http://10740184.blog.51cto.com/10730184/1772313
"C" single linked list of related hot-spot questions (including: printing from the end of the head, reverse, bubbling, looking for the middle node, the reciprocal K-node)