#include<iostream>
using namespace std;
typedef struct node
{
int data;
node *next;
}node;
node* create() //创建单链表,带头结点
{
int i = 0;
node *head, *p, *q;
int x = 0;
head = (node*)malloc(sizeof(node));
q = head;
while (1)
{
cout << "input data" << endl;
cin >> x;
if (x == 0) //输入为0的时候结束建立单链表
break;
p = (node*)malloc(sizeof(node));
p->data = x;
q->next = p;
q = p;
}
q->next = NULL;
return head;
}
int length(node* head) //单链表长度
{
int len = 0;
node* p;
p = head->next;
while (p != NULL)
{
len++;
p = p->next;
}
return len;
}
void print(node* head) //输出单链表
{
node* p;
int index = 0;
if (head->next == NULL)
{
cout << "Link is empty" << endl;
}
p = head->next;
while (p != NULL)
{
cout << "the node is" << p->data << endl;
p = p->next;
}
}
node* search(node* head, int pos) //查找pos位置的结点
{
node* p = head->next;
if (pos < 0)
{
cout << "incorect position" << endl;
return NULL;
}
if (p == NULL)
{
cout << "the link is empty" << endl;
return NULL;
}
if (pos== 0)
return head;
while (--pos)
{
if ((p = p->next) == NULL)
{
cout << "incorrect position" << endl;
break;
}
}
return p;
}
node* insert(node* head, int pos, int data)
{
node* item = NULL;
node* p;
item = (node*)malloc(sizeof(node));
item->data = data;
if (pos == 1)
{
head->next = item;
return head;
}
p = search(head, pos);
if (p != NULL)
{
item->next = p->next;
p->next = item;
}
return head;
}
node* delete_(node*head, int pos)
{
node* item = NULL;
node* p = head->next;
if (p == NULL)
{
cout << "link is empty" << endl;
}
p = search(head, pos-1);
if (p != NULL && p->next != NULL)
{
item = p->next;
p->next = item->next;
delete item;
}
return head;
}
int main()
{
node* head=create();
cout << "length: " << length(head) << endl;
head = insert(head, 2, 5);//在第二个结点(算上表头是第三个)之后插入5
cout << "insert integer 5 after 2th node:" << endl;
print(head);
head = delete_(head, 2);
cout << "after delete 3th node :" << endl;
print(head);
return 0;
}
带头结点单链表操作(数据结构)
最新推荐文章于 2022-11-20 15:00:23 发布