关于链表头插法的思路,怎么敲
提供一下思路,不要太复杂,我看不懂,尽量简单明了,用c++
头插法就是新节点放在开头部分
如果是无哨兵节点的链表,则需要不断修改头节点,新节点成为新的头结点,新节点的next指向原先的头结点就可以了
如果是有哨兵节点的链表,假设为head,新节点为p,那么p->next = head->next,head->next = p就可以了。即新节点的下一个节点为当前头结点的下一个节点,然后当前头结点的下一个节点指向新节点
头插法插入并删除指定位置节点,代码如下:
#include <iostream>
using namespace std;
typedef struct _data
{
int data;
struct _data* next;
}StNode;
int main()
{
int n, i, j;
StNode* head, * p, * t,*front;
head = new StNode;
head->next = 0;
cin >> n;
//头插法
for (i = 0; i < n; i++)
{
t = new StNode;
cin >> t->data;
t->next = head->next;
head->next = t;
}
//输入需要删除的位置
cin >> i;
j = 1;
front = head;
p = front->next;
while (p && j < i)
{
front = p;
p = p->next;
j++;
}
if (p)
{
front->next = p->next;
free(p);
}
else
{
cout << "error";
return 0;
}
if (head->next == NULL)
{
printf("null");
return 0;
}
//输出
p = head->next;
int flag = 0;
while (p)
{
if (flag == 0)
{
flag = 1;
cout << p->data;
}
else
cout << " " << p->data;
p = p->next;
}
return 0;
}
简单点就是
有 struct Node *head,*p
p->next=head
head=p;