程序员面试宝典题目-单链表

1、单链表的建立、测长、打印

单链表建立可以正序建立或者逆序建立。

typedef struct node
{
	int data;
	struct node *next;
}node;
//单链表建立(逆序)
node * Create(node *head, int n)
{
	node *p;
	for(int i=0; i> p->data;
		p->next = head->next;
		head->next = p;
	}

	return head;
}
//单链表建立(正序)
node *Create1(node *head, int n)
{
	node *p = head;
	node *s;
	for(int i=0; i> s->data;
		s->next = NULL;
		p->next = s;
		p = s;
	}
	return head;
}
//单链表长度
int Len(node *head)
{
	int len = 0;
	node *p = head;
	while(p->next != NULL)
	{
		len ++;
		p = p->next;		
	}
	return len;
}
//打印单链表
void Print(node *head)
{
	node *p = head;
	while(p->next != NULL)
	{
		p = p->next;	
		cout << p->data << " ";			
	}	 
	cout << endl;
}
2、删除位置i的元素

先找到第i-1个位置元素,设为p,q = p->next;  p->next = q->next

//删除位置i的元素
node* Delete(node *head, int i)
{
	node *p = head;
	node *q;
	int j = 0;
	if(NULL == head)
		return head;
	while(p->next && j < i-1)
	{
		p = p->next;
		j++;
	}
	if(!(head->next) || (j > i-1))
		return head;
	q = p->next;
	p->next = q->next;
	free(q);
	return head;
}
3、在位置i处插入元素

先找到第i-1个位置的元素,设为p,q->next = p->next; p->next = q;

//在位置i插入元素
node *Insert(node *head, int i)
{
	node *p = head;
	node *q;
	int j = 0;	
	while(p && j < i-1)
	{
		p = p->next;
		j++;
	}
	if(!p || (j > i-1))
		return head;
	q = (node*)malloc(sizeof(node));
	cin >> q->data;
	q->next = p->next;
	p->next = q;
	return head;
}
4、单链表排序(带头结点)
按照冒泡排序的方法

//单链表排序(带头节点)
node *Sort(node *head)
{
	node *p = head->next;
	int i,j,n;
	int tmp = 0;
	n = Len(head);
	if(NULL == head || NULL == head->next)
		return head;
	for(i=1; inext;
		for(j=0; jdata > p->next->data)
			{
				tmp = p->data;
				p->data = p->next->data;
				p->next->data = tmp;
			}
			p = p->next;
		}
	}
}
5、单链表逆置(带头结点)

//单链表逆置(带头结点)
node *Reverse(node *head)
{
	node *p, *p1, *p2, *p3;
	p1 = head->next;
	p2 = p1->next;
	while(p2)
	{
		p3 = p2->next;
		p2->next = p1;
		p1 = p2;
		p2 = p3;
	}
	head->next->next = NULL;
	head->next = p1;
	return head;
}

6、有一单链表,不知道节点数目N,遍历一次,求中间结点。

设立两个指针,*p *q 。p每次移动两个位置,即p = p->next->next,q每次移动一个位置,即q = q->next,当p到达最后一个节点时,q就是中间节点

//不知节点数N,遍历一次求中间节点(有头结点)
node * SearchMid(node *head)
{
	node *mid = NULL;
	node *p = head->next;
	node *tmp = head->next;
	while(p->next != NULL && p->next->next != NULL)
	{
		p = p->next->next;
		tmp = tmp->next;
		mid = tmp;
	}
	return mid;
}

 

你可能感兴趣的:(笔试面试)