leetcode——206——Reverse Linked List

来源:互联网 发布:iphone 手机铃声软件 编辑:程序博客网 时间:2024/04/29 08:44

Reverse a singly linked list.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {  public:      ListNode* reverseList(ListNode* head) {          if(head == NULL || head->next == NULL)              return head;                        if(head->next->next == NULL)          {              ListNode* newhead = head->next;              newhead->next = head;              head->next = NULL;              return newhead;          }                        ListNode* Prev = head;          ListNode* pNode = head->next;         Prev->next = NULL;        ListNode* pTail = pNode->next;                    while(pNode->next!=NULL)          {              pNode ->next = Prev;              Prev = pNode;              pNode = pTail;              pTail = pTail->next;                                      }          pNode ->next = Prev;          return pNode;                          }  };  



0 0