8581 線性鏈表逆置
時間限制:1000MS 代碼長度限制:10KB
提交次數:2811 通過次數:2032
題型: 編程題 語言: G++;GCC
Description
線性鏈表的基本操作如下:
#include<stdio.h>
#include<malloc.h>
#define ERROR 0
#define OK 1
#define ElemType int
typedef int Status;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*LinkList;
Status ListInsert_L(LinkList &L, int i, ElemType e) { // 算法2.9
// 在帶頭結點的單鏈線性表L的第i個元素之前插入元素e
LinkList p,s;
p = L;
int j = 0;
while (p && j < i-1) { // 尋找第i-1個結點
p = p->next;
++j;
}
if (!p || j > i-1) return ERROR; // i小於1或者大於表長
s = (LinkList)malloc(sizeof(LNode)); // 生成新結點
s->data = e; s->next = p->next; // 插入L中
p->next = s;
return OK;
} // LinstInsert_L
Status ListDelete_L(LinkList &L, int i, ElemType &e) { // 算法2.10
// 在帶頭結點的單鏈線性表L中,刪除第i個元素,並由e返回其值
LinkList p,q;
p = L;
int j = 0;
while (p->next && j < i-1) { // 尋找第i個結點,並令p指向其前趨
p = p->next;
++j;
}
if (!(p->next) || j > i-1) return ERROR; // 刪除位置不合理
q = p->next;
p->next = q->next; // 刪除並釋放結點
e = q->data;
free(q);
return OK;
} // ListDelete_L
設有一線性表A=(a0,a1,…, ai,…an-1),其逆線性表定義爲A’=( an-1,…, ai,…,a1, a0),設計一個算法,將線性表逆置,要求線性表仍佔用原線性表的空間。
輸入格式
第一行:輸入n,表示單鏈表的元素個數
第二行:輸入單鏈表的各元素,用空格分開
輸出格式
第一行:輸出單鏈表逆置前的元素列表
第二行:輸出單鏈表逆置後的元素列表
輸入樣例
8
32 97 54 65 35 84 61 75
輸出樣例
The List is:32 97 54 65 35 84 61 75
The turned List is:75 61 84 35 65 54 97 32
#include<stdio.h>
#include<malloc.h>
#define ERROR 0
#define OK 1
#define ElemType int
typedef int Status;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*LinkList;
Status ListInsert_L(LinkList &L, int i, ElemType e) { // 算法2.9
// 在帶頭結點的單鏈線性表L的第i個元素之前插入元素e
LinkList p,s;
p = L;
int j = 0;
while (p && j < i-1) { // 尋找第i-1個結點
p = p->next;
++j;
}
if (!p || j > i-1) return ERROR; // i小於1或者大於表長
s = (LinkList)malloc(sizeof(LNode)); // 生成新結點
s->data = e; s->next = p->next; // 插入L中
p->next = s;
return OK;
} // LinstInsert_L
Status ListDelete_L(LinkList &L, int i, ElemType &e) { // 算法2.10
// 在帶頭結點的單鏈線性表L中,刪除第i個元素,並由e返回其值
LinkList p,q;
p = L;
int j = 0;
while (p->next && j < i-1) { // 尋找第i個結點,並令p指向其前趨
p = p->next;
++j;
}
if (!(p->next) || j > i-1) return ERROR; // 刪除位置不合理
q = p->next;
p->next = q->next; // 刪除並釋放結點
e = q->data;
free(q);
return OK;
} // ListDelete_L
int main()
{
LinkList L1;
L1=(LinkList)malloc(sizeof(LNode));
L1->next=NULL;
int a,each;
scanf("%d",&a);
for(int i=1;i<=a;i++){
scanf("%d",&each);
ListInsert_L(L1,i,each);
}
printf("The List is:");
LinkList t=L1->next;
for(int i=1;i<=a;i++){
printf("%d ",t->data);
t=t->next;
}
printf("\n");
LinkList head=L1,new1=NULL,old1=head->next,tmp;
while(old1){
tmp=old1->next;
old1->next=new1;
new1=old1;
old1=tmp;
}
head->next=new1;
printf("The turned List is:");
LinkList p=head->next;
while(p){
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}