链表是面试中一个重要的内容:
1 实现一个单链表的建立測长,打印
- #include "stdafx.h"
- #include <iostream>
- #include <stdio.h>
- #include <string.h>
- #include <conio.h> //控制台输入输出
- typedef struct student
- {
- int data;
- struct student *next;
- }node;
- //建立单链表
- node* create()
- {
- node *head,*p,*s;
- int x, cycle = 1;
- head = (node *)malloc(sizeof(node));
- p = head;
- while(cycle)
- {
- std::cout<<"please input the data: ";
- std::cin>>x;
- std::cout<<std::endl;
- if(x != 0)
- {
- s = (node *)malloc(sizeof(node));
- s->data = x;
- p->next = s;
- p = s;
- }
- else
- cycle = 0;
- }
- head = head->next;
- p->next = NULL;
- return head;
- }
- //单链表測长
- int length(node *head)
- {
- int n = 0;
- node *p;
- p = head;
- while(p != NULL)
- {
- p = p->next;
- n++;
- }
- return n;
- }
- //单链表打印
- void print(node *head)
- {
- node *p;
- int n;
- n = length(head);
- std::cout<<"Now, These "<<n<<" records are: "<<std::endl;
- p = head;
- if(p != NULL)
- {
- while(p != NULL)
- {
- std::cout<<p->data<<" -> ";
- p = p->next;
- }
- std::cout<<std::endl;
- }
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- node *head;
- head = create();
- print(head);
- return 0;
- }
- int delete(struct Node* x,struct Node* head){
- struct Node* p = head->next;
- struct Node* pre = head;
- if(pre->value == x->value)//推断是否和头部同样
- {
- head=x;
- head->next=p;
- return 0;
- }
- while(p!=NULL)
- {
- if(p->value == x->value){
- pre->next = p->next;
- free(p);
- return 1;
- }else{
- pre = p;
- }
- p = p->next;
- }
- return 0;
- }
3 单链表的插入
- int ListInsert(node *head,int num,node *new)
- {
- node *pre=head;
- node *p=head->next;
- int i=0;
- if(num==0) //开头
- {
- head=new;
- head->next=pre;
- return 0;
- }
- while(p!=NULL) //中间
- {
- if(i=num)
- {
- pre->next=new;
- new->next=p;
- return 0;
- }
- pre=p;
- p=p->next;
- ++i;
- }
- if(p==NULL) //结尾
- {
- p=new;
- new->next=NULL;
- return 0;
- }
- }
4链表排序
<span style="font-size:18px;">void sort(node *head) { node *p1,*p2; p1=head; if(p1->next==NULL) { return; } while(p1) { p2=p1->next; while(p2) { if(p2->data < p1->data) { int temp=p1->data; p1->data=p2->data; p2->data=temp; } p2=p2->next; } p1=p1->next; } } </span>5 对于链表我们能够仅仅遍历一次就能找到中间节点,方法。建立两个指针一个每次加1,还有一个每次加2,当当中一个到达末尾,还有一个则处于中间节点位置。