zoukankan      html  css  js  c++  java
  • 链表的将基本结构及用法

    /*
     * node_2.cpp
     *
     *  Created on: 2013年8月1日
     *      Author: Administrator
     */
    
    #include <iostream>
    
    using namespace std;
    
    typedef int T;//给int起别名为T
    struct Node {
    	T data;
    	Node* next;
    
    	operator T() {
    		return data;
    	}
    	Node(T d) :data(d), next(NULL) {
    
    	}
    
    };
    
    void showList(Node* head) {
    
    	Node* p = head;
    	while (p != NULL) {
    		cout << *p << ' ';
    		/**
    		 * (*p).next == p->next
    		 * p:指向当前结构体的指针
    		 * (*p):当前结构体
    		 * p->next:结构体特有的访问成员变量的方法.其值为某个结构体的地址或者是NULL
    		 * p=p->next :将p指向当前结构体的下一个结构体
    		 *
    		 */
    		p = p->next;
    	}
    
    	cout << endl;
    }
    
    
    int main() {
    
    	Node a(10), b(20), c(30), d(40),e(50),f(60);
    
    	cout<<a<<' '<<b<<endl;//这时会自动调用该结构体的重载的类型转换函数
    
    	a.next = &b;
    	b.next = &c;
    	c.next = &d;
    
    	showList(&a);
    
    	e.next = b.next;
    	b.next = &e;
    
    	showList(&a);
    
    	Node*& r = a.next;
    	f.next = r;
    	r = &f;
    
    	showList(&a);
    
    	Node* k = new Node(70);
    
    	/**
    	 * 访问结构体成员的3种方式:
    	 * c.next :c是结构体变量
    	 * k->next :k是结构体指针(指向结构体的指针)
    	 * (*k).next :k是结构体指针(指向结构体的指针)
    	 */
    	k->next = c.next;
    	c.next = k;
    
    	showList(&a);
    
    
    }
    
    



    以下再贴一个简洁版的:


    /*
     * node_3.cpp
     *
     *  Created on: 2013年8月1日
     *      Author: Administrator
     */
    
    #include <iostream>
    
    
    using namespace std;
    
    typedef int T;
    struct Node{
    	T data;
    	Node* next;
    
    	operator T(){
    		return data;
    	}
    
    	Node(T data):data(data),next(NULL){
    
    	}
    };
    
    void showList(Node* head){
    	Node* p = head;
    
    	while(p!= NULL){
    
    		cout<<(*p)<<' ';
    
    		p=p->next;
    	}
    	cout<<endl;
    }
    
    int main(){
    
    	Node a(10),b(20),c(30),d(40),e(50),f(60);
    
    	a.next = &b;
    	b.next = &c;
    	c.next = &d;
    
    	showList(&a);
    
    	e.next = a.next;
    	a.next = &e;
    	showList(&a);
    
    	Node* & p = b.next;
    	f.next = p;
    	p = &f;
    	showList(&a);
    
    
    	Node* k = new Node(70);
    	k->next = c.next;
    	c.next = k;
    	showList(&a);
    }
    
    
































































  • 相关阅读:
    poj1904 King's Quest
    ACM竞赛须掌握的知识 以及 2个版本的POJ推荐 @ NKOJ discuss 转载的
    poj1466
    C++23中设计模式的factory模式
    poj3667 hotel
    poj1505 Copying Books
    在linux系统中安装VSCode(Visual Studio Code)
    Spring_的jar详细说明
    java开发问题总结4Maven使用问题汇总
    线程同步之信号量(sem_init,sem_post,sem_wait)
  • 原文地址:https://www.cnblogs.com/riskyer/p/3230835.html
Copyright © 2011-2022 走看看