若用C++编写,则如下:
#include<iostream>
using namespace std;
//定义节点类;
class node {
public:
int data;
node *next;
};
//定义单链表类;
class Linklist {
public:
//构造函数
Linklist()
{
head = new node;
head->data = 0;
head->next = NULL;
}
//析构函数;
~Linklist()
{
delete head;
}
//成员函数声明:
void creatlist(); //创建链表;
void printlist(); //打印链表;
private:
node *head;
};
//头插入法;
void Linklist::creatlist()
{
node *s; node *p;
int x;
s = head->next;
cout << "请输入数值" << endl;
while (cin >> x)
{
p = new node;
p->data = x;
head->next = p;
p->next = s;
s = p;
}
}
void Linklist::printlist()
{
node *p;
p = head->next;
while (p != NULL) {
cout << p->data << endl;
p = p->next;
}
}
int main()
{
Linklist ivc1;
ivc1.creatlist();
ivc1.printlist();
system("pause");
return 0;
}
单链表的建立:
#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);
}
单链表中节点的查找
//查找给定的值;
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);
}
单链表上的插入操作
//单链表插入操作;在链表的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;
}
单链表上的删除操作
//单链表的删除: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);
}
}
单链表上的测长操作
//单链表测长;
int length(node *head)
{
node *p; int n = 0;
p = head;
while (p != NULL)
{
p = p->next;
n++;
}
return(n);
}
单链表上的打印操作
//单链表打印;
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;
}
单链表上的逆置操作
<code class="language-html">//单链表的就地逆置:
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;
}</code>
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;
}