双向循环链表实现字符串或int类型数组的左移或右移操作C++

#include "stdafx.h"
#include <iostream>
#include <string.h>
#include <stdio.h>

#define ERROR  0
#define OVERFLOW  -1
#define OK 0x1

typedef int Status;
typedef int ElemType;

typedef struct DNode{
struct DNode *front;
ElemType data;
struct DNode *next;
}DNode,*LinkList;

LinkList GetDNode(LinkList &L,int i);
Status InitList(LinkList &L);
Status ListInsert(LinkList &L,int i, ElemType e);
int ListLength(LinkList &L);

// Init Double loop list table
Status InitList(LinkList &L)
{
L =(LinkList)malloc(sizeof(DNode));
if(!L)  return OVERFLOW;
L->next = L; 


L->front = L;
return OK;
}


// Insert double loop list table
Status ListInsert(LinkList &L,int i, ElemType e)
{
LinkList P,S;
if(i<1 || i>ListLength(L)+1)  return ERROR;


P = GetDNode(L,i-1);
S = (LinkList)malloc(sizeof(DNode));
if(!S)  return OVERFLOW;


S->next  = P->next;
P->next = S;
S->data = e;
S->front = P;

L->front = S;


//if(S->next)
// S->next->front = S;


return OK;
}

// Get the pre-Node of the current node
LinkList GetDNode(LinkList &L,int i)
{
LinkList P;
P = L;
for(int j=1;j<=i;++j)
{
P = P->next;
}
return P;
}

// calculate the length of double list
int ListLength(LinkList &L)
{
int i = 0;
LinkList P;
P = L->next;
while(P!=L)
{
P = P->next;
++i;
}
return i;
}


void Travese(LinkList &L, void (*visit)(ElemType e))
{
LinkList P;
P = L->next;
while(P!=L)
{
visit(P->data);
P = P->next;
}
}


void print(ElemType e)
{
printf("%d\n",e);
}


void Shift(int* Input,int n, int shiftN)
{
LinkList head,P;
InitList(head);
int i,j;
for(i=1;i<=n;++i)
ListInsert(head,i,Input[i-1]);
// Travese(head,print);
if(shiftN < 0)
{
P = head;
for(i=0;i<abs(shiftN);i++)
P =P->next;
   P=P->next;
for(j=0;j<n;j++)
{
Input[j] = P->data;
P = P->next;
if(P == head)
P = P->next;
}

}
if(shiftN > 0)
{
P = head;
for(i=0;i<abs(shiftN);i++)
P = P->front;
P = P->front;
for(j=n-1;j>=0;j--)
{
Input[j] = P->data;
P = P->front;
if(P == head)
P = P->front;
}

}
}

int _tmain(int argc, _TCHAR* argv[])
{



int a[]={1,2,3,4,5,6,7,8,9};
int len = sizeof(a)/4;
Shift(a,len,-2);
int i;
for(i=0;i<len;i++)
printf("%4d",a[i]);
printf("\n");
Shift(a,len,2);
for(i=0;i<len;i++)
printf("%4d",a[i]);

return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值