[剑指offer-1518]反转链表

来源:互联网 发布:linux下解压rpm文件 编辑:程序博客网 时间:2024/06/05 03:53

题目描述:
输入一个链表,反转链表后,输出链表的所有元素。
(hint : 请务必使用链表)
输入:
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(0<=n<=1000):代表将要输入的链表的个数。
输入的第二行包含n个整数t(0<=t<=1000000):代表链表元素。
输出:
对应每个测试案例,
以此输出链表反转后的元素,如没有元素则输出NULL。
样例输入:
5
1 2 3 4 5
0
样例输出:
5 4 3 2 1
NULL

#include <stdio.h>#include <stdlib.h>typedef struct Node{    int value;    struct Node* next;}Node,*pNode;pNode reverseList(pNode head){    if(head == NULL || head->next == NULL)        return  head;    pNode prev, cur, next;    prev = head;    cur  = head ->next;    prev->next = NULL;    while (cur) {        next = cur->next;        cur->next = prev;        prev = cur;        cur = next;    }    head = prev;    return head;}pNode createList(int n){    pNode head = NULL;    pNode current = NULL;    while(n--){        int value;        scanf("%d",&value);        pNode newNode = (pNode)malloc(sizeof(Node));        newNode->value =value;        newNode->next = NULL;        if(head == NULL){            head = newNode;            current = head;        }else{            current->next = newNode;            current = current->next;        }    }    return head;}void printList(pNode head){    if(head == NULL){        printf("NULL\n");        return;    }    pNode tmp = head;    while (tmp) {        if(tmp->next == NULL)            printf("%d\n",tmp->value);        else            printf("%d ",tmp->value);        tmp = tmp->next;    }}int main(int argc, const char * argv[]) {    // insert code here...    int n;    while (scanf("%d",&n)!=EOF) {        pNode head = createList(n);        pNode tmp = reverseList(head);        printList(tmp);    }    return 0;}
0 0
原创粉丝点击