看似简单的一个链表算法问题,帮忙下,谢谢啊

来源:百度知道 编辑:UC知道 时间:2024/06/08 19:43:59
对于一个给定的线性链表,编写一个程序,其功能是完成把值为a的结点插在值为b的结点的前面。若值b的结点不在线性链表中,则把a插在链表的最后。
用C++写出相应程序,并做出相应注释。

查了些资料,关键的插入功能做不出来,谁帮忙做下啊,我头都晕了...
#include "iostream.h"
#include "string.h"

typedef struct SList //定义链表结构
{
char elem;
struct SList * next;
} SL;
SL * create_list(); //函数create_list用于建立空链表
int insert_list(SL * head,char * elem,int n);//函数insert_list用于在链表中插入新结点
void brow_list(SL * head); //函数brow_list用于浏览链表

void main()
{
SL *head; //定义链表头指针
char elem;
head=NULL; //初始化头指针
head=create_list();
//输入元素,插入,浏览
}
SL * create_list() //建立空链表
{
SL * head;
head=new SL; //为头结点分配存储空间
if(head!=NULL) //确保链表成功建立,并返回相应信息
cout<<"链表已建立!\n";
else
cout<<"没有足够内存空间!\07\n"

不太容易做,#include "iostream.h"
#include "string.h"

typedef struct SList//定义链表结构
{
char elem[8];
struct SList * next;
} SL;
SL * create_list(); //函数create_list用于建立空链表
int insert_list(SL * head,char * elem);//函数insert_list用于在链表中插入新结点
int insert_list(SL * head,char * elem)
{
SL * p,* q,* s;
q=head; //指针初始化
p=head->next;//p指向第一个结点
while(p!=NULL) //当链表未到尾结点时循环
{
q=p;//让p指向下一结点
p=p->next;
}
s=new SL;//为新结点分配存储空间
if(s==NULL)
{
cout<<"没有足够内存空间!\07\n";
return 0;//插入失败返回0
}
q->next=s;//将新结点s加入到链表中
s->next=p;
strcpy(s->elem,elem);//将元素存入新结点
return 1;//插入成功返回1
}

你写成什么样子了?发出来,我帮你改。

/*假设你的节点结构是
struct node{
int num;
struct node* next;
};

你的链表已经存在一部分内容,指向头的指针是*head然后插入..
*/

struct node* InsertNode(struct