单链表逆序
2015-08-28 21:19
399 查看
#include<iostream> using namespace std; typedef struct node { int data; struct node *next; }Node, *List; //建立带头结点的单链表 List createList() { Node *head, *p1, *p2; p1 = p2 = head = new Node;//头结点 int num; cin >> num; while(-1 != num) { p1 = new Node; p1->data = num; p2->next = p1; p2 = p1; cin >> num; } p2->next = NULL; //不可少 return head; } int getListLength(List p) { int length = 0; while(NULL != p->next) { length++; p = p->next; } return length; //不包括头结点 } //把element插入到第position个位置 List insertNode(List p, int position, int element) { int length = getListLength(p); if(position < 1 || position > length + 1) { cout << "wrong position" << endl; exit(1); } Node *p1 = p ->next; Node *p2 = p; int i; for(i = 0; i < position - 1; i++) { p2 = p1; p1 = p1->next; } Node *s = new Node; s->data = element; p2->next = s; s->next = p1; return p; } List delNode(List p, int num) { Node *p1 = NULL, *p2 = NULL; if(NULL == p->next) return p; p1 = p->next; p2 = p; //不可少 //注意while中条件的顺序 while(NULL != p1 && num != p1->data) { p2 = p1; p1 = p1->next; } //注意if中条件的顺序 if(NULL == p1) cout << "not been found" << endl; else { p2->next = p1->next; delete p1; } return p; } void printList(List p) { while(NULL != p->next) { cout << p->next->data << " "; p = p->next; } cout << endl; } //下面采用递归释放(也可循环释放) void releaseList(List p) { if(NULL == p->next) delete p; else { releaseList(p->next); delete p; } } int main() { List head = createList(); printList(head); int position = 4; int element = 100; head = insertNode(head, position, element); printList(head); int num = 3; head = delNode(head, num); printList(head); releaseList(head); return 0; }
相关文章推荐
- 第一个socket编程(python)
- UIActivityIndicatorView
- Linux kernel的中断子系统之:IRQ Domain介绍
- 前言
- 不使用Main.storyboard
- 代理转发器
- JavaScript基础-arguments
- hdu 3527 Task Schedule 最大流 Dinic
- 数据结构课程主页-2014级
- [转]在树莓派上搭建LAMP服务
- 常用的CSS Hack技术集锦
- Note on <Beginning Microsoft SQL Server 2012 Programming> - 03
- 自定义Dialog;Notification;PopupWindow;DatePickerDialog;TimePickerDialog
- 多线程总结
- UIAlertView
- Linux kernel的中断子系统之综述
- Select 函数
- Mars Chen培训之真机调试android程序
- mysql
- 《IOS_C语言》while|循环,do...while循环,for循环