【C】字符串和链表元素的反转



    比较简单的C语言笔试题,自己写了一下,记录

    字符串反转



    #include <stdio.h>
    
    char *reverse(char *str)
    {
         int len = strlen(str);
         int steps = len / 2;
         int i, j;
         for(i=0; i< steps; i++)
         {
             j = len - 1 - i;
             str[i] = str[j] ^ str[i];
             str[j] = str[j] ^ str[i];
             str[i] = str[j] ^ str[i];
         }
         return str;
    }
    
    int main(int argc, char *argv[])
    {
        char s[] = "abcdef!";
        printf("%s\n", s);
        reverse(s);
        printf("%s\n", s);
    
        return 0;
    }

    链表元素反转

    #include <stdio.h>
    
    typedef struct node
    {
        struct node *next;
        int val;
    } Node;
    
    Node *create(int n)
    {
        Node *head = NULL, *p = NULL, *cur=NULL;
        while(n--)
        {
            p = (Node*)malloc(sizeof(Node));
            p->val = n;
            p->next = NULL;
            if (head == NULL)
            {
                cur = head = p;
            }
            else
            {
                cur->next = p;
                cur = p;
            }
        }
        return head;
    }
    
    void print(Node *head)
    {
        Node *p = head;
        while(p != NULL)
        {
            printf("%d ", p->val);
            p = p->next;
        }
        printf("\n");
    }
    
    Node *reverse(Node *head)
    {
        Node *cur, *q, *p = head;
        if (p == NULL || p->next  == NULL)
        {
            return p;
        }
        else
        {
            q = p->next;
            cur = reverse(p->next);
            q->next = p;
            p->next = NULL;
            return cur;
        }
    }
    
    int main(int argc, char *argv[])
    {
        Node *head = create(10);
        print(head);
        head = reverse(head);
        print(head);
        return 0;
    }

    P.S.

    1. 判断链表是否有环及两链表是否相交
    2. 逆序数/逆序数对


    本博客所有文章如无特别注明均为原创。
    复制或转载请以超链接形式注明转自枫芸志,原文地址《【C】字符串和链表元素的反转
    标签:
    分享:

还没有人抢沙发呢~

无觅相关文章插件,快速提升流量