最近复习了线性表,对链表这一部分遗忘最大,所以手动实现一下单链表的增,删,改,查,倒置等等加深理解,附上C++代码:
#include<iostream> using namespace std; typedef struct LNode { //定义链表的结构 int data; struct LNode* next; }LNode,*LinkList; void create(LinkList& l) // 头插法建立带头结点的链表,输入小于0的数值视为终止 { l = (LinkList)malloc(sizeof(LNode)); int x; l->next = NULL; cin >> x; do { LNode* s = (LNode*)malloc(sizeof(LNode)); s->data = x; s->next = l->next; l->next = s; cin >> x; } while (x > 0); }
void tailCreate(linkList& l)
{
l = (linkList)malloc(sizeof(LNode));
int data;
l->next = NULL;
cin >> data;
linkList ptr = l;
while (data > 0)
{
linkList p = (linkList)malloc(sizeof(LNode));
p->data = data;
ptr->next = p;
p->next = NULL;
ptr = p;
cin >> data;
}
}
void dis(LinkList l) //输出链表 { cout << "当前链表为:"<<endl; while (l->next != NULL) { cout << l->next->data << " "; l = l->next; } cout << endl; } LinkList insert(LinkList& l, int x) //头插法插入结点在链表开头 { LNode* s = (LNode*)malloc(sizeof(LNode)); s->data = x; s->next = l->next; l->next = s; return l; } int getNumber(LinkList l, int x)//按照值查找结点序号,返回序号 { int i = 0; while (l != NULL) { i++; if (l->data == x) { cout << "find x=" << x << " ,num=" << i - 1 << endl; break; } l = l->next; } return i; } LNode* getElement(LinkList l, int no)//按照序号查找结点并返回结点 { LNode* s = l->next; int j = 1; while (s->next != NULL && j < no) { s = s->next; j++; } cout <<"find No."<<no<<" is "<< s->data << endl; return s; } void delect(LinkList& l, int no)//删除指定序号的节点 { if (no == 1) //因为第一个元素的前驱结点是头结点,所以单独处理删除第一个元素的情况 { LNode* s = l; LNode* p = l->next; l->next = p->next; free(p); } else { LNode* s = getElement(l, no - 1); //先找到它的前驱结点 LNode* p; p = s->next; s->next = p->next; cout << "delect " << p->data << " success" << endl; free(p); } } void reverseList(LinkList& l) //将链表倒序 { LNode* s = (LNode*)malloc(sizeof(LNode)); LNode* p = (LNode*)malloc(sizeof(LNode)); s = l->next; l->next = NULL; while (s!= NULL) { p = s->next; s->next = l->next; l->next = s; s = p; } } int main(void) { LinkList l; int x, no; cout << "输入正整数插入链表,输入负整数后结束输入:" << endl; create(l);//输入链表 dis(l); //输出链表 cout << "输入要插入在链表前端的数值:" << endl; cin >> x; insert(l,x); dis(l); cout << "输入要查找的结点数值:" << endl; cin >> x; getNumber(l,x);//根据数组查找第一个对应的结点 cout << "输入要查找的结点序号(1~n):" << endl; cin >> no; getElement(l,no);//根据序号查找对应的数值 cout << "输入要删除的结点序号(1~n):" << endl; cin >> no; delect(l,no);//删除指定序号的结点 dis(l); reverseList(l);//反转链表 dis(l); }
执行上述程序的输出如下: