連結串列相應操作
阿新 • • 發佈:2018-12-11
連結串列
#include <map> #include <cmath> #include <queue> #include <cstdio> #include <string> #include <cstring> #include <iostream> #include <algorithm> #include <sstream> #include <time.h> #include <vector> #include <list> #include <stack> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; //建立一個具有n個節點的連結串列,從鍵盤輸入資料將其初始化,並返回連結串列的首節點指標 ListNode *createNode(int n) { ListNode *pHead(0), //首節點指標 *pRear(0), //尾節點指標 *pNew; //新節點指標 int i; for (i = 0; i<n; i++) { pNew = new ListNode(0); cin >> pNew->val; if (0 == i) { pRear = pHead = pNew; } else { pRear->next = pNew; } pNew->next = NULL; pRear = pNew; } return pHead; } //輸出連結串列中的內容 void printNode(ListNode *pHead) { ListNode *pTemp = pHead; while (pTemp != NULL) { cout << pTemp->val; pTemp = pTemp->next; } cout << endl; } //查詢連結串列中具有指定值的節點,並返回此節點指標 ListNode *searchNode(ListNode *pHead, int val) { ListNode *pDest = pHead; while (pDest->next != NULL && pDest->val != val) pDest = pDest->next; if (pDest->val == val) return pDest; else return NULL; } ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int a = 0, b = 0; int num = 0; ListNode *LL = l1; while (LL != NULL) { a += LL->val*pow(10, num); num++; LL = LL->next; } LL = l2; num = 0; while (LL != NULL) { b += LL->val*pow(10, num); num++; LL = LL->next; } int c = a + b; cout << c << endl; ListNode *out, *save(0); //呼叫前必須分配空間(指標賦值) out = new ListNode(0); out->val = c % 10; save = out; while ((c /= 10)) { ListNode *front; front = new ListNode(0); front->val = c % 10; save->next = front; save = front; } save->next = NULL; return out; } int main() { int i, j, N, M; //m和n分別表示畫布的寬度和高度,q表示畫圖操作的個數 cin >> N ; ListNode *P = createNode(N); printNode(P); ListNode *q = createNode(N); printNode(q); ListNode * out = addTwoNumbers(P, q); printNode(out); cin >> N >> M; return 0; }