反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

 

 

注意:这个链表有效值是从head开始而不是head->next开始的
下面的代码没有动指针只是改值了,不是很推荐,但是通过了测试,有时间再写动指针的方法吧
c++代码如下:
 
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* head) {
    ListNode *p=head;
    int top=0;
    vector<int> res;    
    if(p==NULL) return NULL;
    while(p)
    {
    res.push_back(p->val);
    p=p->next;    
    }reverse(res.begin(),res.end());
    p=head;
    while(p){
        p->val=res[top];
        top++;p=p->next;
    }    
 return head;
    }
};

 用栈:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
    Stack<Integer> stk = new Stack<>();
    ListNode temp = head;
    while(temp!=null){
        stk.add(temp.val);
        temp=temp.next;
    }
    int size=stk.size();
    int []res = new int[size];
    for(int i=0;i<size;i++){
     res[i]=stk.pop();
    }
    return res;
}
}

 

 不用栈

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
    
    ListNode temp = head;
    int size=0;
    while(temp!=null){
        size++;
        temp = temp.next;      
    }
    int top=size-1;
    int []res = new int [size];
    temp=head;
    while(temp!=null){
    res[top--]=temp.val;
    temp=temp.next;
    }
    return res;

}
}

 操作指针(更建议这种解法:双指针)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
    if(head==null) return null;
    ListNode pre=head,cur=pre.next,tmp;
    pre.next=null;
    while(cur!=null){
    tmp=cur.next;//cur未指向pre时先保存它的next节点
    cur.next=pre;
    pre=cur;
    cur=tmp;
    }
    return pre;
    }
}

 

 

 



posted @ 2019-07-24 11:06  浅滩浅  阅读(131)  评论(0)    收藏  举报