链表 常数附加空间反转

#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <iterator>
#include <stack>
#include <cstdlib>

using namespace std;

const int N = 10010;

typedef struct node List;

struct node
{
int val;
List *next;
};

List* MakeEmpty(List *l)
{
if (l != NULL)
{
MakeEmpty(l -> next);
free(l);
}
l = NULL;
return l;
}

List* inst(int x, int k, List *l)
{
List *p, *t;

if (l == NULL)
{
l = (struct node*) malloc(sizeof (l));
l -> val = x;
l -> next = NULL;
return l;
}

else if (!k)
{
p = (struct node*) malloc(sizeof (List));
p -> val = x;
p -> next = l;
l = p;
return l;
}

p = (struct node*) malloc(sizeof (List));
t = l;
int idx = 1;
while (l != NULL)
{
if (l -> next == NULL || idx == k)
{
p -> val = x;
p -> next = l -> next;
l -> next = p;
return t;
}

idx ++;
l = l -> next;
}
}

List* del(int x, List *l)
{
List* t = l;
if (l -> val == x)
{
l = l -> next;
free(t);
return l;
}

while (l -> next != NULL)
{
if (l -> next -> val == x)
{
List *p = l -> next;
l -> next = p -> next;
free(p);
return t;
}
l = l -> next;
}

puts("No Found!");
return t;
}

int find(int x, List *l)
{
if (l == NULL) return -1; // 空表返回-1

int idx = 1;
while (l != NULL)
{
if (l -> val == x) return idx;

idx ++;
l = l -> next;
}

return -1; // 未找到该元素
}

List* rev(List *l)
{
List *t = l;
List *p1 = l, *p2 = p1 -> next, *p3;

while (p2)
{
p3 = p2 -> next;
p2 -> next = p1;
p1 = p2;
p2 = p3;
}
t -> next = NULL;

return p1;
}

void print(List *l)
{
if (l == NULL)
{
puts("Empty!");
return;
}

while (l != NULL)
{
printf("%d ", l -> val);
l = l -> next;
}
}

int main()
{
int n, x, k;
List *L = NULL;

cin >> n;
for (int i = 1; i <= n; i ++)
{
scanf("%d", &x);
L = inst(x, i, L);
}

// 在位置k后插入
//cin >> k >> x;
//inst(x, k, L);

// 删除元素x
//cin >> x;
//del(x, L);

// 查找x的位置
//cin >> x;
//cout << find(x, L) << endl;

// 复杂操作: 常数附加空间 及 O(n) 反转单链表
L = rev(L);

// 打印链表
print(L);
return 0;
}

posted @ 2020-10-30 20:41  ctxcc  阅读(139)  评论(0)    收藏  举报