《单链表倒序算法》由会员分享,可在线阅读,更多相关《单链表倒序算法(2页珍藏版)》请在金锄头文库上搜索。
1、单链表倒序算法 #include #include using namespace std; struct st int a; st(int i) a = i; struct st* next; ; void sort(struct st* /排序后的链表头 st* p1 = head;/排序前的链表头 st* p2 = p1;/在排序过程中,保存原始链表头 for(;p2;) p2 = p1-next;p1-next = p;/以上 2 步,是将当前节点从链表中取出然后将指针反向指向p = p1;/将排序好的链表的头,给 pp1 = p2;/将 p1 重新指向链表的首位置 head = p;
2、/让 head 重新指向排序好的链表头 void print(struct st* p) for(;p;) cout a next; int main( void ) st* head = new st(0); st* p = head;p-next = new st(1); p = p-next; p-next = new st(2); p = p-next; p-next = new st(3); p = p-next;p-next = 0;print(head); sort(head); cout next? sort(tmp-next, h)-next=tmp, tmp-next=0, tmp: (h=tmp);