05_從尾到頭列印鏈表,05尾到頭列印

來源:互聯網
上載者:User

05_從尾到頭列印鏈表,05尾到頭列印

#include <iostream> #include <vector>using namespace std;typedef struct ListNode {int data;struct ListNode * next;ListNode(int d) : data(d), next(NULL){}};ListNode *initList() {ListNode * head = NULL;ListNode * p = NULL;int number = 10;int i = 0;head = new ListNode(0);p = head;for(i = 1; i < number; i++) {p->next = new ListNode(i);p = p->next;}return head;} void printList(ListNode *head) {ListNode * p = head;if (!head){return;}while (p && p->next) {cout<<p->data<<"->";p = p->next; }if (p) {cout<<p->data<<endl;}}//using vector to store the ListNode->data, and print it from the end to startvoid reversePrintListUsingVector(ListNode *head){vector <int> vec;if(!head) {return;}ListNode *p = head;while (p) {vec.push_back(p->data);p = p->next;}for (vector<int>::size_type i = vec.size() - 1; i > 0; i--) {cout<<vec[i]<<"->";}cout<<vec[0]<<endl;} //change the ListNode:delete the head->next and insert the deleted node after the newHead;ListNode *reversePrintList(ListNode *head){if(!head) {return NULL;}ListNode *deletedNode = head;ListNode *oldHead = head;ListNode *tempHead = new ListNode(0);while(oldHead) {deletedNode = oldHead; oldHead = oldHead->next;deletedNode->next = tempHead->next;tempHead->next = deletedNode;}ListNode * reserverdhead = tempHead->next;delete tempHead; return reserverdhead; } void main(){ /********In the first way, the List was not changed, but we need a vector to store the list*************/ListNode * head = initList();cout<<"initial List:"<<endl;printList(head);cout<<"the first way to reverse the List:"<<endl;reversePrintListUsingVector(head);/********In the second way, the List was changed and we need to new a listNode*************/cout<<endl;cout<<"initial List:"<<endl;printList(head);cout<<"the second way to reverse the List:"<<endl;head = reversePrintList(head);printList(head);}


輸入一個鏈表的頭結點,從尾到頭反過來輸出每個結點的值 為何不會輸出結果,

p0= (node* ) malloc(sizeof(node));
p1= (node* ) malloc(sizeof(node));

p2= (node* ) malloc(sizeof(node));

p3= (node* ) malloc(sizeof(node));

在主函數裡面多加4句話
要給p0,p1,p2,p3,p4分配記憶體空間
 
編寫一個讀入一個字串,把它存入一個鏈表,並按相反的次序列印的程式

如果必須是鏈表的話就定義一個雙向鏈表 比如這樣的
struct WORD
{
char a;
WORD* next;
WORD* prev;
}
存的時候用next串連 列印的時候用prev列印
scanf("%c",temp);
WORD* p;
p=(WORD*)malloc(sizeof(WORD));
剩下代碼自己考慮一下吧
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.