在OJ上做了几道链表操作的题目,通过和别人代码的比较也尽量使代码简洁了一些。
SDUT 2116 ~ 2122.
struct node{ int val; node *next; node(){ val = 0; next = NULL; } };
node* normalCreat(int n){ //正常的顺序读入 建立链表 node *head,*p,*rear; head = new node; rear = head; //用rear来操纵 for(int i=0;i<n;i++){ p = new node; scanf("%d",&p->val); rear->next = p; rear = rear->next; } return head; //返回头节点 } node* reverseCreat(int n){ //逆向建立链表 node *head,*p; int i; head = new node; for(int i=0;i<n;i++){ p = new node; scanf("%d",&p->val); p->next = head->next; //这里的写法很巧妙 head->next = p; } return head; }
node* mergeList(node *a,node *b){ //返回合并后的两个链表, (并未删除原来的链表) a = a->next; b = b->next; node *head = new node ; node *c = head; while(a && b){ if(a->val > b->val){ c->next = b; b = b->next; c = c->next; } else{ c->next = a; a = a->next; c = c->next; } } while(a){ c->next = a; a = a->next; c = c->next; } while(b){ c->next = b; b = b->next; c = c->next; } return head; }
node *odd,*even; //奇数表, 偶数表 int oddNum,evenNum; void divideList(node* head){ //将链表中分成两个链表 1.奇数链表 2.偶数链表 even = new node; odd = new node; node* rear_even = even; node* rear_odd = odd; node* rear = head; rear = rear->next; while(rear){ if(rear->val % 2){ oddNum++; rear_odd->next = rear; rear = rear->next; rear_odd = rear_odd->next; rear_odd->next = NULL; } else{ evenNum++; // cout<<rear->val<<" bug"<<endl; rear_even->next = rear; rear = rear->next; rear_even = rear_even->next; rear_even->next = NULL; } } }
int del(node* head,int n){ //链表中 删除重复的元素 node *p,*q,*t; p = head->next; while(p->next != NULL){ q = p; t = q->next; while(t->next != NULL){ if(t->val == p->val){ q->next = t->next; delete t; t = q->next; n--; } else{ q = t; t = t->next; } } if(t->next == NULL){ if(t->val == p->val){ q->next = NULL; delete t; n--; } } p = p->next; } return n; }
node* orCreat(int n){ //有序建立链表, 无序的读入数据,建立ascend(有序递增的表) node *head,*p,*rear; head = new node; rear = head; for(int i=0;i<n;i++){ p = new node; rear = head; scanf("%d",&p->val); if(rear->next != NULL){ while(1){ if(rear->next->val>= p->val){ p->next = rear->next; rear->next = p; break; } else rear = rear->next; if(rear->next == NULL){ rear->next = p; break; } } } else head->next = p; } return head; }
void show(node *head){ //打印链表的元素 node *p; p = head->next; while(p!=NULL){ if(p->next != NULL) printf("%d ",p->val); else printf("%d\n",p->val); p = p->next; } }