本文主要是介绍创建无头结点单链表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#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;
}
这篇关于创建无头结点单链表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!