链表面试题
我也不知道该叫什么.就叫 链表折叠 吧
题目:
给一个单链表,形如
1 2 3 4 5
变成
1 5 2 4 3
算法复杂度要求为O(n)
思路:
- 先把后半部分反转过来,
- 然后把后半部分 和 前半部分 合并.
用到的知识点:
- 构建单链表
- 链表反转
- 链表合并(这个其实相当于插入了一个节点)
- 遍历单链表
# include <bits/stdc++.h>
using namespace std;
struct node{
int x;
struct node * next;
node(int a,struct node * b):x(a),next(b) {
}
};
node * head;
//输入单链表
void input(int n)
{
int x;
node * cur;
for( int i = 0;i < n;i++)
{
scanf("%d",&x);
node *tem = new node(x,NULL);
if(head == NULL)
{
head = tem;
cur = head;
}else{
cur->next = tem;
cur = cur->next;
}
}
}
//遍历单链表
void show(node * p)
{
printf("\n=============================\n");
while(p != NULL)
{
printf("%d ",p->x);
p = p-&