【MAC 上学习 C++】Day 55-8. 实验11-2-9

2019-10-18  本文已影响0人  RaRasa

实验11-2-9 链表逆置 (20 分)

1. 题目摘自

https://pintia.cn/problem-sets/13/problems/607

2. 题目内容

本题要求实现一个函数,将给定单向链表逆置,即表头置为表尾,表尾置为表头。链表结点定义如下:

struct ListNode {
int data;
struct ListNode *next;
};

函数接口定义:

struct ListNode *reverse( struct ListNode *head );
其中head是用户传入的链表的头指针;函数reverse将链表head逆置,并返回结果链表的头指针。

输入样例:

1 2 3 4 5 6 -1

输出样例:

6 5 4 3 2 1

3. 源码参考
#include <iostream>
#include <stdlib.h>

using namespace std;

struct ListNode {
    int data;
    struct ListNode *next;
};

struct ListNode *createlist(); /*裁判实现,细节不表*/
struct ListNode *reverse( struct ListNode *head );
void printlist( struct ListNode *head )
{
     struct ListNode *p = head;
     while (p) {
           printf("%d ", p->data);
           p = p->next;
     }
     printf("\n");
}

int main()
{
    struct ListNode  *head;

    head = createlist();
    head = reverse(head);
    printlist(head);
    
    return 0;
}

struct ListNode *createlist()
{
  struct ListNode *p, *h, *t;
  int n;

  h = NULL;
  cin >> n;
  while(n != -1)
  {
    p = (struct ListNode*)malloc(sizeof(struct ListNode));
    
    p->data = n;
    p->next = NULL;
    
    if(h == NULL)
    {
      h = p;
    }
    else
    {
      t->next = p;
    }
    
    t = p;
    cin >> n;
  }
  
  return h;
}

struct ListNode *reverse( struct ListNode *head )
{
  struct ListNode *pPre, *pCur, *pNext;
  
  pPre = head;
  pCur = pPre->next;
  pNext = NULL;
  while(pCur)
  {
        pNext = pCur->next;
        pCur->next = pPre;
        pPre = pCur;
        pCur = pNext;
  }

  head->next = NULL;
    head = pPre;        //记录下新的头结点

  return head;
}
上一篇下一篇

猜你喜欢

热点阅读