剑指offer--反转链表

题目:输入一个链表,反转链表后,输出反转链表后头节点

思路1: 扫描 即开始翻转,直到文件结束 返回最后一个指针。

代码如下:

/*struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
	ListNode* ReverseList(ListNode* pHead) {
        ListNode * current;
        ListNode * pre=NULL;
        ListNode * tmp = NULL;
        ListNode * rHead=NULL;
        
        current = pHead;
        while(current!=NULL){
             tmp= current->next;
             current->next = pre;
             if(tmp== NULL){
                 rHead = current;
             }
             pre = current;
            current = tmp;
            
        }
        return rHead;

	}
};

思路2 : 使用栈 可以轻松搞定


/*struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
	ListNode* ReverseList(ListNode* pHead) {
        ListNode * current;
        current = pHead;
        ListNode * rHead;
        stack stack1;
        
        while(current->next!=NULL){
            stack1.push(current);
            current = current->next;
        }
        rHead=current;
        while(!stack1.empty()){
            current->next = stack1.top();
            
            current=current->next;
        stack1.pop();
        }
        current->next = NULL;
        
        return rHead;


	}
};


你可能感兴趣的:(面试与面试题解析)