单链表翻转

84 阅读1分钟

使用语言:c++。

#include <iostream>
using namespace std;

//链表
struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int val, ListNode *next = NULL) :val(val), next(next){}
};

//翻转链表
ListNode* ReverseList(ListNode* head){
    ListNode *p = NULL,*q=NULL;
    while (head)
    {
        q = head->next;
        head->next =p;
        p = head;
        head = q;       
    }
    return p;
}
//输出
void printList(ListNode* head){
    ListNode *p = head;
    while (p)
    {
        cout << p->val<<" ";
        p = p->next;
    }
    cout << endl;
}

int main()
{
    ListNode *head=NULL,*p=NULL,*tail=NULL;
    //反向构造数据,没有头结点
    for (int i = 0; i < 10; i++)
    {
        p = new ListNode(i);
        p->next = head;
        head = p;
    }

    printList(head);

    tail = ReverseList(head);

    printList(tail);

    return 0;
}

程序输出:

9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
请按任意键继续. . .