萨芬的


私信TA

用户名:19891218

访问量:3810

签 名:

等  级
排  名 16640
经  验 753
参赛次数 0
文章发表 6
年  龄 0
在职情况 学生
学  校 撒旦法
专  业

  自我简介:


解题思路:


其实,后移对于链表来说 只需要让头节点顺着前驱向前移动便可

改变了头节点得位置之后 从当前头结点顺序往后输出



注意事项:





参考代码:#include <stdio.h>
#include <stdlib.h>
typedef struct NODE{
int value;
struct NODE *previous,*next;
}node;
//函数声明
node *create();
void output(node *head);
void freeNode(node *head);
node *swapHead(node *head,int n);
node *input();
//主函数
int main(){
    int n;
node *head=NULL;
head=input();
scanf("%d",&n);
head=swapHead(head,n);
output(head);
//system("pause");
freeNode(head);
return 0;
}
//接收数值
node* input(){
    node *temp,*head=NULL;
int n ,value;
scanf("%d",&n);
while (n--)
{
scanf("%d",&value);
if (head)  //如果头节点非空
{
temp->next=create();   //临时节点后继指向新节点
temp->next->previous=temp; //临时节点后继(新节点)的前驱指向前节点
temp=temp->next;//后移至新节点
head->previous=temp; //头前驱指向新节点 
temp->next=head;        //新节点后继指向头节点 形成循环链表
temp->value=value;      //新节点赋值
}else{ //否则头节点为空(初始情况)的情况下对头结点赋值
head=create();
temp=head;
head->value=value;
}
}
return head;
}
//交换头
node * swapHead(node *head,int n){
while (n--)  //如果n不为空 执行循环并自减1
{
head=head->previous; //头节点顺着前驱前移
}
return head;
}
//创建
node * create(){
node *add=NULL;
add=(node*)malloc(sizeof(node));  //申请空间

   //初始化

add->value=0;
add->previous=NULL;
add->next=NULL;
    return add;
}
//打印
void output(node *head){
    node *temp=head;
do{
//    printf("%d %p<-%p->%p\n",temp->value,temp->previous,temp,temp->next);
    printf("%d ",temp->value);
    temp=temp->next;
}while (temp!=head); //先打印头 然后临时节点往后走 如果没有走回头就继续循环 否则退出循环
}
//释放
void freeNode (node *head){
node *temp,*current=head;
while (current->next!=head)
{
current=current->next;
free(current->previous);
current->previous=NULL;
}
free(current);
current=NULL;
}

 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区