• 创建单链表


    还记得创建单链表的这些代码还是大学时候写过,现在再重新写一写,为面试做准备吧:

    创建单链表的两种形式:头插法和尾插法

    // 演示创建2种单链表的方式
    // 【C++基础】单链表.cpp
    
    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    struct link {
    	int data;
    	link *next;
    };
    
    //头插法建立单链表
    link *creatLink_head(link *head) {
    	link *node;
    	int tmpData;
    	cout << "输入元素,以空格分隔:";
    	do {
    		cin >> tmpData;
    		if (tmpData == 0)
    			break;
    
    		node = new link;
    		node->data = tmpData;
    		node->next = head->next;
    		head->next = node;
    
    	} while (node->data != 0);
    	return head->next;
    }
    
    //尾插法建立单链表
    link *creatLink_tail(link *head) {
    	link *node, *tail = head;
    	int tmpData;
    	cout << "输入元素,以空格分隔:";
    	do {
    		cin >> tmpData;
    		if (tmpData == 0)
    			break;
    		node = new link;
    		node->data = tmpData;
    		tail->next = node;
    		tail = node;
    		tail->next = NULL;
    	} while (tmpData != 0);
    	return head->next;
    }
    
    //遍历输出
    void printLink(link *p){
    	while (p != NULL) {
    		cout << p->data << "  ";
    		p = p->next;
    	}
    	cout << endl;
    }
    int main()
    {
    	link *head, *p_head, *p_tail;
    	head = new link;
    	head->next = NULL;
    	//方式1:头插法创建单链表
    	//p_head = creatLink_head(head);
    	//printLink(p_head);
    
    	//方式2:尾插法创建单链表
    	p_tail = creatLink_tail(head);
    	printLink(p_tail);
    	
        return 0;
    }
    
  • 相关阅读:
    HDoj-2072-字数
    hibou 主界面自己侧滑的定义
    Android得到一个闹钟在第三方
    UILabel,UITextField 以及UIButton应用
    推荐几个好文章
    半年后,我还在路上。
    NGUI 3.5过程(三)Button button
    OpenGL研究2.0 计算圆
    CF 444A(DZY Loves Physics-低密度脂蛋白诱导子图)
    美日高价进口中国非转基因大豆:不仅吃还做药
  • 原文地址:https://www.cnblogs.com/xuelisheng/p/9225810.html
Copyright © 2020-2023  润新知