zoukankan      html  css  js  c++  java
  • 线性表——双向链表

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <ctime> 
    
    using namespace std;
    
    using ElemType = int;
    
    // 双向链表结点 
    class Node {
    public:
    	ElemType data;
    	Node *next;
    	Node *prior; 
    }; 
    
    // 初始化链表 
    void initList(Node *head, int n)
    {
    	srand(time(NULL));
    	Node *p = head, *r = head;
    	while (n--) {
    		Node *q = (Node*)malloc(sizeof(Node));
    		q->data = rand()%100 - 1;
    		p->next = q;
    		q->prior = p;
    		q->next = r;
    		r->prior = q;
    		p = q;
    	}
    }
    
    // 增加某结点 
    void addNode(Node *head, int i, ElemType val)
    {
    	int j = 0;
    	Node *p = head;
    	while (1) {
    		if (j == i - 1) {
    			Node *q = (Node*)malloc(sizeof(Node));
    			q->data = val;
    			q->prior = p;
    			q->next = p->next;
    			p->next->prior = q;
    			p->next = q;
    			break;
    		}
    		j++;			// p指向第j个结点 
    		p = p->next;
    	}
    }
    
    // 删除某结点 
    void delNode(Node *head, int i)
    {
    	int j = 0;
    	Node *p = head;
    	while (1) {
    		if (j == i) {
    			p->prior->next = p->next;
    			p->next->prior = p->prior;
    			break;
    		}
    		j++;
    		p = p->next;
    	}
    }
    
    // 取某结点的值 
    void getNode(Node *head, int i)
    {
    	int j = 0;
    	Node *p = head;
    	while (1) {
    		if (j == i) {
    			cout << "第" << i << "个结点的值为:" << p->data << endl;
    			break;
    		}
    		j++;
    		p = p->next;
    	}	
    }
    
    // 打印双向链表 
    void print(Node *head)
    {
    	Node *p = head;
    	p = p->next;
    	while (p != head) {
    		cout << p->data << " ";
    		p = p->next;
    	}
    	cout << endl;
    }
    
    
    int main()
    {
    	Node *head = (Node*)malloc(sizeof(Node));
    	head->prior = head;
    	head->next = head;
    	initList(head, 5);
    	print(head);
    	addNode(head, 2, 100);
    	print(head);
    	delNode(head, 2);
    	print(head);
    	getNode(head, 2);
    }
    

      

  • 相关阅读:
    转:sql语句中GROUP BY 和 HAVING和使用 count()
    shell中的大括号和小括号
    转:关于rename命令ubuntu下的用法
    Linux批量重命名
    STL 源代码剖析 算法 stl_algo.h -- partition
    HDU 5091 线段树扫描线
    IBM 中国研究院面试经历
    当人手一部智能手机时 庞大的数据中心们已死
    Treap的读书笔记2
    【JUnit4.10源码分析】5 Statement
  • 原文地址:https://www.cnblogs.com/xzxl/p/8643001.html
Copyright © 2011-2022 走看看