反转链表

来源:互联网 发布:php菱形 编辑:程序博客网 时间:2024/05/17 01:29

面试题16:反转链表


提交网址: http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168

或 https://leetcode.com/problems/reverse-linked-list/


Total Accepted: 101523  Total Submissions: 258623  Difficulty: Easy

Reverse a singly linked list.


Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?


  • 参与人数:5517  时间限制:1秒  空间限制:32768K
  • 本题知识点:链表

分析:

使用头插法,并每次将newhead获取到最前端临时结点(整体赋值)...

有空了,再来用递归思想实现一次...


AC代码:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. class Solution {  
  2. public:  
  3.     ListNode* ReverseList(ListNode* pHead) {  
  4.   
  5.         ListNode *p;  
  6.         ListNode *newhead=NULL;  
  7.         p=pHead;  
  8.           
  9.         if(pHead==NULL || pHead->next==NULL)  return pHead;  
  10.           
  11.         while(p!=NULL)  
  12.         {  
  13.             ListNode *temp=p;  
  14.             p=p->next;  
  15.               
  16.             temp->next=newhead;         // 挂接上     
  17.             newhead=temp;                  // 将新插入的节点整体复制给头指针结点  
  18.         }  
  19.        return newhead;          
  20.     }  
  21. };  
0 0