您的位置:首页 > 理论基础 > 数据结构算法

单链表的建立,查找,插入,删除,测长,打印,逆置操作实现

2018-03-22 19:59 751 查看
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<conio.h>

using namespace std;

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

//建立单链表,头插入法;
node *creatlist()
{
node *head, *p, *s;
int x;

//申请新的存储空间,创立头节点;
head = (node*)malloc(sizeof(node));
head->next=NULL;  //重要   指针需要初始化;
s = head->next;

cout << "用头插法建立单链表, 请输入链表数据, 以 ctrl+z 结束" << endl;

while ( cin>>x)
{
p = (node*)malloc(sizeof(node));
p->data = x;
head->next = p;
p->next = s;
s = p;
}

return(head);
}
2.  单链表中节点的查找操作

//查找给定的值;
node *locate(node *head, int x)
{
node *p;
p = head->next;
while (p != NULL && p->data != x)
{
p=p->next;
}
if (p == NULL)
cout << "链表中不存在这个数" << endl;
return (p);

}
3.  单链表上的插入操作

//单链表插入操作;在链表的p节点后插入x;
void insert(node *p, int x)
{
node *q;

q = (node*)malloc(sizeof(node*));
q->data = x;
q->next = p->next;
p->next = q;

}
4.  单链表上的删除操作

//单链表的删除:p指向需要删除的节点,q为跟踪节点,指向被删除的直接前驱节点;
void deletelist(node *head, int x) //需要从头开始找;
{
node *p, *q;
q = head; p = q->next;//容易忘记;
while (p != NULL && p->data != x)
{
q = p;
p = p->next;
}
if (p == NULL)
{
cout << "找不到需要删除的节点" << endl;
}
else {
q->next = p->next;
free(p);
}

}

5.  单链表上的测长操作

//单链表测长;
int length(node *head)
{
node *p; int n = 0;
p = head;
while (p != NULL)
{
p = p->next;
n++;
}
return(n);
}


6.  单链表上的打印操作

//单链表打印;
void print(node *head)
{
node *p;
p = head->next;
cout << "当前单链表的具体数据为:" << endl;
while (p != NULL)
{
//p = p->next;
cout << p->data << endl;
p = p->next;
}
//cout << endl;
}


7.  单链表上的逆置操作
//单链表的就地逆置:
node* ReverseList(node* pHead)
{
if (pHead == NULL || pHead->next == NULL)
{
return pHead;
}

node* pRev = NULL;
node* pCur = pHead;
while (pCur != NULL)
{
node* pTemp = pCur;   // 步骤①
pCur = pCur->next;       // 步骤②
pTemp->next = pRev;      // 步骤③
pRev = pTemp;
}
return pRev;
}
最后是main函数;
int main()
{
node *head,*pRev;
head = creatlist();     //建立单链表;

cout<<locate(head, 5)<<endl; //查找元素5的位置;

insert(head, 88);        //在表头插入88;

deletelist(head, 7);      //在链表中删除元素7;

cout << length(head) << endl;   //单链表测长;

print(head);           //打印链表;

pRev=ReverseList(head);    //就地逆置;

print(pRev);

system("pause");
return 0;
}


  


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐