编程实现单链表和双链表的插入节点

来源:互联网 发布:剑网三怎么在淘宝代练 编辑:程序博客网 时间:2024/04/16 13:15

编辑程序实现单链表的插入

#include <tchar.h>#include <iostream>using namespace std;typedef struct student{int data;struct student * next; } node;node* create(){node *head, *p, *s;int x, cycle = 1;head = (node *)malloc(sizeof(node));p = head;while(cycle){cout << "please input the data: ";cin >> x;cout << endl;if( x != 0){s = (node *)malloc(sizeof(node));s->data = x;p->next = s;p = s;}else{cycle = 0;}}p->next = NULL;head = head->next;return head;}int length(node *head){int n = 0;node *p;p = head;while (p != NULL){p = p->next;n++;}return n;}void print(node *head){int n;node *p;p = head;n = length(head);cout << "There is " << n << " data in list\n" << endl;while(p != NULL){cout << p->data << " -> ";p = p->next;}cout << endl;}node *insert(node *head, int num){node *p0, *p1, *p2;p1 = head;p0 = (node *)malloc(sizeof(node));p0->data = num;while(p0->data > p1->data && p1->next != NULL){p2 = p1;p1 = p1->next;}if(p0->data <= p1->data){if(head == p1)//头插入{p0->next = p1;head = p0;}else//中间插入{p2->next = p0;p0->next = p1;}}else//尾插入{ p1->next = p0;p0->next = NULL;}return head;}int _tmain(int argc, _TCHAR * argv[]){node *head;head = create();print(head);head = insert(head, 4);print(head);return 0;}

双链表插入

#include <tchar.h>#include <iostream>using namespace std;typedef struct student{int data;struct student * next;struct student * pre;} node;node* create(){node *head, *p, *s;int x, cycle = 1;head = (node *)malloc(sizeof(node));p = head;while(cycle){cout << "please input the data: ";cin >> x;cout << endl;if( x != 0){s = (node *)malloc(sizeof(node));s->data = x;p->next = s;s->pre = p;p = s;}else{cycle = 0;}}p->next = NULL;head = head->next;head->pre = NULL;return head;}int length(node *head){int n = 0;node *p;p = head;while (p != NULL){p = p->next;n++;}return n;}void print(node *head){int n;node *p;p = head;n = length(head);cout << "There is " << n << " data in list\n" << endl;while(p->next != NULL){cout << p->data << " -> ";p = p->next;}cout << p->data << endl;while(p->pre !=NULL){cout << p->data << " -> ";p = p->pre;}cout << p->data << endl;}node *insert(node *head, int num)  {      node *p0, *p1, *p2;      p1 = head;      p0 = (node *)malloc(sizeof(node));      p0->data = num;      while(p0->data > p1->data && p1->next != NULL)      {          p2 = p1;          p1 = p1->next;     }      if(p0->data <= p1->data)      {          if(head == p1)  //头插入        {              p0->next = p1;  p1->pre = p0;            head = p0;          }          else  //中间插入        {  p1->pre->next = p0;p0->pre = p1->pre;p1->pre = p0;p0->next = p1;        }      }      else  //尾插入    {          p1->next = p0;          p0->next = NULL;  p0->pre = p1;    }      return head;  }  int _tmain(int argc, _TCHAR * argv[]){node *head;head = create();print(head);head = insert(head, 3);print(head);return 0;}



原创粉丝点击