栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C 无头链表,右移位数。得到新串。

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C 无头链表,右移位数。得到新串。

改变字符的顺序,不用额外存储空间。
改变前:a1 a2......am b1 b2......bn
改变后:b1 b2......bn a1 a2......am
如A B C D E F G变成E F G A B C D。用链表实现。

#define _CRT_SECURE_NO_WARNINGS
#include 
#include
typedef struct Node {
    char val;
    struct Node* next;  
}ListNode;

ListNode* rotate(ListNode* head, int k) {
    if (k == 0 || head == NULL || head->next == NULL) return head;
    int n = 1;
    ListNode* iter = head;
    while (iter->next != NULL) {
        iter = iter->next;
        n++;
    }
    int add = n - k % n;
    if (add == n) return head;
    iter->next = head;
    while (add--) iter = iter->next;
    ListNode* ret = iter->next;
    iter->next = NULL;
    return ret;
}

ListNode* creatlist_r(char str[],int n)
{
    int i;
    ListNode*head=NULL,*p,*r=NULL;    
    for (i = 0; i < n; i++)
    {
        p= (ListNode*)malloc(sizeof(ListNode));
        p->val = str[i];
        p->next = NULL;
        if (head == NULL)
        {
            head = p; 
            r = p;
        }
        r->next = p;
        r = p;
    }
    return head;
}
void print(ListNode* head)
{
    if (head == NULL)
        return;
    ListNode* p = head;
    while (p)
    {
        printf("%c ",p->val);
        p = p->next;
    }
    printf("n");
}
int main()
{  
    ListNode* head;
    char str[] = { 'A','B','C','D','E','F','G' };
    head=creatlist_r(str,7);
    head = rotate(head,3);//右移3  
    print(head);
    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/836412.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号