leetcode之链表-单链表反转-C++

ReverseLinked List

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

迭代版本:


1.	/** 
2.	 * Definition for singly-linked list. 
3.	 * struct ListNode { 
4.	 *     int val; 
5.	 *     ListNode *next; 
6.	 *     ListNode(int x) : val(x), next(NULL) {} 
7.	 * }; 
8.	 */  
9.	class Solution {  
10.	public:  
11.	    ListNode* reverseList(ListNode* head) {  
12.	        ListNode *p;  
13.	        ListNode *q;  
14.	        ListNode *r;  
15.	          
16.	        if(head == NULL || head->next == NULL)  
17.	        {  
18.	            return head;  
19.	        }  
20.	        else  
21.	        {  
22.	            p = head;  
23.	            q = head->next;  
24.	            head->next = NULL;  
25.	              
26.	            while(q)  
27.	            {  
28.	                r = q->next;  
29.	                q->next = p;  
30.	                p = q;  
31.	                q = r;  
32.	            }  
33.	            head = p;  
34.	        }  
35.	        return head;  
36.	    }  
37.	};  


你可能感兴趣的:(LeetCode)