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);
    }
    

      

  • 相关阅读:
    贪心法
    div 样式
    echarts标题(title)配置
    利用svg画路径图 vue
    vue 杂项
    Charset 0x0408D00000/MS936 is not supported by the JVM
    Android开发中Eclipse常用快捷键
    Java 中强制删除文件的方法
    利用html5的localStorage结合jquery实现日常费用查询器
    Ant编译utf8非法字符:/65279 解决方法
  • 原文地址:https://www.cnblogs.com/xzxl/p/8643001.html
Copyright © 2011-2022 走看看