1. 程式人生 > >建立無頭結點單鏈表

建立無頭結點單鏈表

#include "stdafx.h"
#include <iostream>
using namespace std;

typedef int ElemType;
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    //建立無頭結點的單鏈表
    ListNode* Create(void)
    {
        char s;
        ListNode *tail = NULL;
        ListNode *head = NULL;
        while
(1) { ListNode *tmp = new ListNode(0); //定義一個s節點用來存放每次要輸入的值 scanf("%d", &tmp->val); if (head == NULL) { head = tmp; } else { tail->next = tmp; } tail = tmp; s = getchar(); if
(s == '\n') { break; } } if (tail != NULL) tail->next = NULL; return head; } //輸出無頭結點單鏈表 void List(ListNode *L) { ListNode *p; p = L; // while (p != NULL) { printf("%2d", p->val); p = p->next; } } }; int
main() { ListNode *L1; int temp; printf("請輸入連結串列:\n"); L1 = Solution().Create(); printf("無頭結點的連結串列為:\n"); Solution().List(L1); system("pause"); return 0; }