本文主要是介绍单链表尾插法1、2,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include <iostream>
using namespace std;
typedef char DataType;
typedef struct node{
DataType data;
struct node * next;
}ListNode;
typedef ListNode * LinkList;
LinkList CreateListR(){ //方法1
char ch;
LinkList head;
ListNode *s,*r;
head=NULL;
r=NULL;
while((ch=getchar())!='x'){
s=(ListNode *)malloc(sizeof(ListNode));
s->data=ch;
if(head==NULL){
head=s;
}
else{
r->next=s;
}
r=s;
}
if(r!=NULL){
r->next=NULL;
}
return head;
}
LinkList CreateListR1(){ ///方法2
char ch;
LinkList head=(LinkList)malloc(sizeof(ListNode));
ListNode *s,*r;
r=head;
while((ch=getchar())!='x'){
s=(ListNode *)malloc(sizeof(ListNode));
s->data=ch;
r->next=s;
r=s;
}
r->next=NULL;
return head;
}
//按第i个位置查找
ListNode * GetNode(ListNode head,int i){
int j;
ListNode *p;
p=head;
j=0;
while(p->next && j<i){
p=p->next;
j++;
}
if(i==j){
return p;
}
else{
return NULL;
}
}
//按值查找
ListNode *LocateNode(ListNode head,DataType key){
ListNode *p=head->next;
while(p&&p->data!=key){
p=p->next;
}
return p;
}
void InsertList(LinkList head,DataType x,int i){
ListNode *p;
p=GetNode(head,i-1);
if(p==NULL){
cout<<"ERROR"<<endl;
}
s=(ListNode *)malloc(sizeof(ListNode));
s->data=x;
s->next=p->next;
p->next=s;
}
void DeleteList(LinkList head,int i){
ListNode *p,*r;
p=GetNode(head,i-1);
if(p==NULL || p->next==NULL){
cout<<"ERROR"<<endl;
}
r=p->next;
p->next=r->next;
free(r);
}
int main(){
CreateListR1();
system("pause");
}
这篇关于单链表尾插法1、2的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!