#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);
}
}
5. 單鏈表上的測長操作
//單鏈表測長;
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;
}
//單鏈表的就地逆置: 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;
}
若用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;
}