双向链表
双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。一般我们都构造双向循环链表。
 
A 的data 是1,他的next一个节点,指向 B ,B的prev指向A,这是那来了 C,C 的 data 是2,C要想插入到 A ,B中间,只需改变next,perv 指向即可!
这样可以排序!
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication4 { class DoubleLinkedList { private Node head; public void Add(int data) { if (head==null) { head = new Node(data); } else { head=head.Add(new Node(data)); } } public override string ToString() { if (head==null) { return string.Empty; } else { return this.head.ToString(); } } public class Node { //节点的值 private int data; private Node next; private Node prev; public Node(int data) { this.data = data; } public int Data { get { return this.data; } } public Node Add(Node newNode) { if (data > newNode.data) //传进来的值大于当前值 { newNode.next = this;//把传进来的值放到当前值前面去 if (this.prev!=null)//前面不为空 { this.prev.next = newNode; newNode.prev = this.prev; } this.prev = newNode; //设置当前节点的前一个节点为新节点 return newNode;//只有新节点为头节点时才返回 } else { if (this.next!=null) {//递归 this.next.Add(newNode); } else { this.next = newNode;//设置新节点为当前节点的下一节点 newNode.prev = this; } return this; } } public override string ToString() { string str = data.ToString(); if (next!=null) { str += " " + next.ToString(); } return str; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { DoubleLinkedList lst = new DoubleLinkedList(); lst.Add(1); lst.Add(3); lst.Add(9); lst.Add(2); lst.Add(6); lst.Add(5); lst.Add(8); Console.WriteLine( (lst.ToString())); Console.ReadLine(); } } }

                    
                
                
            
        
浙公网安备 33010602011771号