接[C/C++开发工程师必知]:单链表几种编程实现(上)主要有:
实现单链表删除节点、实现单链表插入节点和单链表逆置
4.实现单链表删除节点 代码如下: node *del(node *head,int num) { node *p1,*p2; p1 = head; while(num != p1->data && p1->next !=NULL) {p2 = p1;p1 = p1->next; } if(num == p1->data) { if(p1==head) { head = p1->next; free(p1); } else p2->next = p1->next; } else printf("\n%d could not been found",num); return(head); }
5.实现单链表插入节点 代码如下: node *insert(node *head,int num) { node *p0,*p1,*p2; p1 = head; p0 =(node *)malloc(sizeof(node)); p0->data = num; while(p0->data > p1->data && p1->next != NULL) {p2 = p1;p1 = p1->data;} if(p0->data <= p1->data) { if(head == p1) { p0->next = p1; head = p0; } else { p2->next = p0; p0->next = p1; } } else { p1->next = p0; p0->next = NULL; } return(head); }
6.单链表逆置 代码如下: node *reverse(node *head) { node *p1,*p2,*p3; if(head == NULL || head->next == NULL) return head; p1 = head; p2 = p1->next; while(p2) { p3 = p2->next; p2->next = p1; p1 = p2; p2 = p3; } head->next = NULL; head =p1; return head; }
int main() { node *head,stud; int n,del_num,insert_num; head = creat(); print(head); cout<<"\nInt"; cin>>del_num; head = del(head,del_num); print(head); cout<<"\n please input the insert data: "; cin>>insert_num; head = insert(head,insert_num); print(head); return 0; }
|
阅读(832) | 评论(0) | 转发(0) |