leetcode: 翻转链表

翻转一个链表

样例

样例 1:

输入: 1->2->3->null
输出: 3->2->1->null

样例 2:

输入: 1->2->3->4->null
输出: 4->3->2->1->null

挑战

在原地一次翻转完成

 

#include <stdio.h>
#include <stdlib.h>

struct linklist{
int val;
struct linklist *next;
};

struct linklist *revert(struct linklist *head)
{
    struct linklist *tmp, *p;

    if (!head)
        return;

    p = head->next;
    if (!p) //one node
        return;

    tmp = p->next;
    if (!tmp) {// 2 nodes
        head->next->next = head;
        head->next = NULL;
        head = p;
    }

    //more than 2 nodes
    head->next = NULL;
    p->next = head;

    head = p;
    p = tmp;
    tmp = p->next;

    while (tmp) {
        p->next = head;

        head = p;
        p = tmp;
        tmp = p->next;
    }
    p->next = head;
    head = p;

    return head;
}

int main()
{
    int data[5] = {1,2,3,4,5}, i;

    struct linklist *t, *tmp = NULL;

    for (i=0; i<5; i++) {
        t = (struct linklist *)malloc(sizeof(struct linklist));
        t->val = data[i];
        t->next = tmp;
        tmp = t;
    }

    while (tmp) {
        printf("%d ", tmp->val);
        tmp = tmp->next;
    }
    printf("\n");
    tmp = revert(t);
    while (tmp) {
        printf("%d ", tmp->val);
        tmp = tmp->next;
    }
    printf("\n");
}
 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页