单链表的创建+ 求表长+ 查找+插入+删除
2015-11-07 19:32
399 查看
#include<iostream> #include<stdlib.h> #include<stdio.h> using namespace std; struct node{ int data ; struct node * next ; } ; //建立单链表,返回头结点 struct node * CreateLinkList(){ char ch ; int x ; struct node * head ; struct node * r , * P ; head = (struct node *)malloc(sizeof(struct node)) ; head->next = NULL ; r = head ; ch =getchar( ) ; while(ch != '*'){ // cout<<"ch = " << ch<< endl; scanf("%d" , & x) ; // cout<<"x = " << x << endl; P = (struct node *) malloc(sizeof(struct node)) ; P->data = x ; P->next = NULL ; r->next = P ; r = r-> next ; ch = getchar( ) ; } return head ; } //输出头结点为head表的单链表 void PutOut(struct node * head){ struct node * p = head ; while(p->next != NULL){ p = p->next ; cout<<p->data << endl; } } //求头结点为head表表长 int LengthLinkList( struct node * head){ struct node * P = head ; int j = 0 ; while(P-> next != NULL){ P = P->next ; j++ ; } return j ; } //元素的查找 //1在头结点为head表的单链表中查找值为x的节点,并返回其位置 struct node * LocateLinkList( struct node * head , int x){ struct node * p = head->next ; while(p!= NULL && (p->data != x)){ p = p-> next ; } return p ; } //2在单链表head中查找第i个元素并返回其位置,无第i个元素返回NULL struct node * GetLinkList(struct node* head , int i){ struct node * p = head ; int j = 0 ; while( j < i && (p->next != NULL)){ p = p -> next ; j++ ; } if(j == i) return p ; else{ return NULL ; } } //插入 //在头结点为head表的单链表中第i个位置上插入值为x的元素 struct node* insertLinkList(struct node * head , int x , int i){ struct node * p , * s ; p = GetLinkList(head , i- 1 ) ; //找到第i个节点的前驱 if(p == NULL){ printf("第i-1个元素不存在,参数i有错\n") ; } else{ s = (struct node *) malloc(sizeof(struct node)) ; s->data = x ; s->next = p->next ; p->next = s ; } return head ; } //删除单链表head中第i个节点 , 并返回链表 struct node * deleteLinkList(struct node * head , int i){ struct node * p = GetLinkList(head , i - 1) ; struct node * s ; if(p == NULL) printf("第i-1个元素不存在, 参数i有错 \n") ; else{ s = p->next ; p->next = s->next ; free(s) ; } return head ; } int main(){ int i , x; cout<<"建立单链表:(请输入【空格】1 2 3 4 5 6 7*)"<< endl; struct node * h = CreateLinkList() ; cout<<"显示单链表"<< endl; PutOut(h) ; int len = LengthLinkList(h) ; cout<<"该链表的表长 = " << len << endl; struct node * r , *r1; r = LocateLinkList(h , 2) ; cout<<"输出查找x = 2并返回其位置"<< endl; cout << r->data << endl; while(r->next != NULL){ r = r->next ; cout<< r->data << endl; } r = GetLinkList(h , 3) ; cout<<"输出查找第3个元素,并返回其位置"<< endl; cout << r->data << endl; while(r->next != NULL){ r = r->next ; cout<< r->data << endl; } cout<<"在head单链表中第i个位置插入值为x,并返回链表"<< endl; cout<<"请输入x"<< endl; scanf("%d" , &x) ; cout<<"请输入i"<<endl; scanf("%d" , &i) ; r1 = insertLinkList(h, x , i ) ; cout<<"输出插入元素后的链表" << endl; PutOut(r1) ; cout<<"删除h单链表中第i个元素,并返回链表"<< endl; cout<<"请输入i"<< endl; scanf("%d" , &i) ; r1 = deleteLinkList(h , i) ; cout<<"输出删除后的链表" << endl; PutOut(r1) ; return 0 ; }