现在的位置: 首页 > 综合 > 正文

单链表实现创建,查找,删除,插入等操作

2013年08月22日 ⁄ 综合 ⁄ 共 1917字 ⁄ 字号 评论关闭

      以前在学校的时候,想破头也不太会明白什么时候会用到数据结构,链表等知识写点程序,那个时候就觉得用点asp写点网站比较好看,有成就感。哎,可出来了明白了。事实远不是那样。就web开发那点知识也恐怕算不上程序员哦。说了废话这么多,先写点简单的知识。单链表的各种操作。希望还在学校的学弟学妹们。一定要好好学习数据结构,算法等知识哈。要想进好公司,这些必不可少啊。

 

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

struct node
{
 int data;
 struct node *next;
};

node* create()
{
 node *head,*s,*p;
 int x;
 head = (struct node*)malloc(sizeof(struct node));
 head->next = NULL;
 cout << "x=";
 cin >> head->data;
 p=head;
 while(x!=-1)
 {
  s=(struct node*)malloc(sizeof(struct node));
  cout << "x=";
  cin >> x;
  s->data = x;
  s->next = NULL;
  p->next = s;
  p = s;
 }
 return head;
}
void print(node *head)
{
 if(head == NULL)
  return;
 while(head!=NULL)
 {
  cout << head->data << ' ';
  head=head->next;
 }
}
void search(node *head, int num)
{
 int index=1;
 if(head==NULL)
  return;
 while(head!=NULL&&head->data!=num)
 {
  head=head->next;
  index++;
 }
 if(head==NULL)
 {
  cout << "sorry, don't find num " <<endl;
 }
 else
 {
  cout << "ok, you find: " << head->data << endl;
  cout << "the index of: " << index << endl;
 }
}
/***n为插入位置,num为插入元素**/
void insert(node *p, int n, int num)
{
 node *s,*h;
 s=(struct node*)malloc(sizeof(struct node*));
 s->data=num;
 bool ins = false;
 int i=1;
 while(p->next!=NULL&&p->next->data!=num)
 {
  p=p->next;
  i++;
  if(i==n)
  {
   s->next = p->next;
   p->next = s;
   ins = true;
   break;
  }
 }
 if(ins)
 {
 }
 else
 {
  s->next = p->next;
  p->next = s;
 } 
}
void deletes(node *head, int num)
{
 node *q;
 if(head==NULL)
  return;
 while(head->next!=NULL&&head->next->data!=num)
 {
  head=head->next;
 }
 if(head->next==NULL)
 {
  cout << "don't find the num which you want to delete!" << endl;
 }
 else
 {
  q=head->next;
  head->next = q->next;
  free(q);
  cout << "delete successful" << endl;
 }
}

int main()
{
 node *head,*searchpiont;
 int num,n;
 head = create();
 print(head);
 cout << endl;
 cout << "please the num which you want to find: " ;
 cin >> num;
  search(head, num);
  cout << "please the num which you want to delete: " ;
 cin >> num;
 deletes(head, num);
 print(head);
 cout << "please the num which you want to insert and index: " ;
 cin >> n >>num;
 insert(head, n, num);
 print(head);
}

抱歉!评论已关闭.