反转单链表

来源:互联网 发布:python 传入函数 编辑:程序博客网 时间:2024/05/22 08:14
///题不难 思路也很容易理清 只是在实现的过程中老走歪路 唉 我智障 /*#include <iostream>using namespace std;struct node{    node *next;    int data;};int main(){    node *L1, *L2;    L1 = new node;    L1->next = NULL;    L2 = new node;    L2->next = NULL;    node *p, *q;    q = L1;    for(int i=1; i<=5; i++){        p = new node;        p->next = NULL;        p->data = i;        q->next = p;        q = p;    }    ///我的思想就是把值从前到后赋给数组 然后导致在赋给链表 是不是觉得很麻烦    ///呵呵哒 我也这么觉得 于是我又想了几招 只实现了一种    p = L1->next;    int a[100];    int i = 0;    while(p){        a[i] = p->data;        i++;        p = p->next;    }    p = L1->next;    while(p)    {        p->data = a[i-1];        cout << p->data << ' ';        p = p->next;        i--;    }    return 0;}*////我突然 灵光一现 可以尝试把链表做成环 不行啊啊啊啊啊啊啊啊啊///突然 我又有想法了///废话少说 试试再说#include<iostream>using namespace std;struct node{    int data;    node *next;};int main(){    node *L1;    node *p, *q;    L1 = new node;    L1->next = NULL;    q = L1;    for(int i=1; i<=5; i++)    {        p = new node;        p->next = NULL;        p->data = i;        q->next = p;        q = p;    }/*    int i = 0;    cout << endl;    cout << p << endl;    cout <<p->next << endl;    while(p)    {        cout << "1" << endl;        q = new node;        q = p;/// there is a problem 我把p付给q之后 那么q就是p啦 对q操作就相当于对p操作 然后q后置空就相当于p后置空        cout << p << endl;///p后面的就全没了 这个问题唬了我好久啊啊啊啊啊啊啊        cout << q << endl;///在修改指针未果的情况下 我决定采用赋值的方式 这回应该没问题了        if(i == 0)    ///还得先用个数组把值取出来 然后前插法  感觉还是麻烦 就不能不用数组吗  终于成功了 没用数组         {               ///哈哈哈哈   但是正常人应该不会用这么长时间吧 唉 智障儿童除了比常人努力之外 好像也没别的办法了            q->next = NULL;        }        else        {            q->next = p1;        }        cout << p->next << endl;        cout <<q->next << endl;        p1 = p1->next;        p2 = p2->next;        p = p->next;        i++;    }*/    node *p2,*q2, *L2;    p = L1->next;    q = L1;    L2= new node;    L2->next = NULL;    int i = 0;    while(p)    {        p2 = new node;        p2->data = p->data;        if(i == 0)///在L2后面插        {            p2->next = NULL;            L2->next = p2;        }        else///在L2 和  L2->next 中间插        {            p2->next = L2->next;            L2->next= p2;        }        p = p->next;        i++;    }    p = L2->next;    while(p)    {        cout << p->data << ' ';        p = p->next;    }    return 0;}/*1 2 3 4 5*/

0 0
原创粉丝点击