天天看点

反转链表(剑指offer)

反转链表

  • 参与人数:1754时间限制:1秒空间限制:32768K
  • 通过比例:28.31%
  • 最佳记录:0 ms|8552K(来自  pgxxhh)

题目描述

输入一个链表,反转链表后,输出链表的所有元素。 题目链接:http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目很简单吧,就是把一个单链表反转,注意一点,反转后尾指针的next要指向NULL; 反转的思路是先令指针p=pHead;然后令指针q=pHead->next;接着pHead=q->next;最后反转前面的位置q->next=p;p=q; 循环!

面试题不是很难,但要细心,我还不够细心。要做一个缜密的程序猿,加油!

#include<stdio.h>
#include<iostream>
using namespace std;

typedef struct ListNode
{
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
} ListNode,*LinkList;

class Solution
{
public:
    ListNode* ReverseList(ListNode* pHead)
    {
        ListNode *p,*q,*en;
        p=pHead;
        en=p;
        if(pHead)/**注意头指针为空的情况,考虑要周详*/
        {
            if(pHead->next)
            {
                q=pHead->next;
                while(q->next)
                {
                    pHead=q->next;
                    q->next=p;
                    p=q;
                    q=pHead;
                }
                pHead->next=p;
                en->next=NULL;
            }
        }

        return pHead;
    }
    void CreatList(LinkList &L,int n)
    {
        LinkList q,p;
        //      L=(LinkList)malloc(sizeof(ListNode));
        L=new ListNode(NULL);
//       L->next=NULL;//创建一个不带带头结点的单链表
        p = L; //L为头结点
        if(n>0) cin>>p->val;
        int x;
        for(int i=0; i<n-1; i++)
        {
            cin>>x;
            q=new ListNode(x);

            p->next=q;
            p = q ;
        }
    }
};
int main()
{
    Solution so;
    int n;
    scanf("%d",&n);
    ListNode* L;
    so.CreatList(L,n);
    ListNode* ans=so.ReverseList(L);
    while(ans)
    {
        printf("%d\t",ans->val);
        ans=ans->next;
    }
    // vector<int>::iterator it;
//    printf("%d\n",ans[0]);
//   for(it=ans.begin();it!=ans.end();it++)
//       printf("%d\t",*it);
    return 0;
}

           

继续阅读