剑指offer——反转链表

反转链表

输入一个链表,反转链表后,输出链表的所有元素。

 

在这里注意:

在反转的链表最后,有一个操作:

在stack中第一个压入的结点的next是指向第二个结点的,在最后要改成null,才能改成最后一个结点

 

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
import java.util.Stack;
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        Stack<ListNode> st = new Stack<>();
        while(head != null){
            st.push(head);
            head = head.next;
        }
        ListNode node = st.pop();
        ListNode reHead = node;
        while(!st.empty()){
            node.next = st.pop();
            node = node.next;
        }
        node.next = null;
        return reHead;
    }
}

  

别人的思路

就是定义一个前驱结点preNode,一个后继结点pNext

pNext = pNode.next;(记录当前节点的下一个结点)

pNode.next = preNode;(将当前节点的下一个结点指向前驱节点)

preNode = pNode;(将前驱节点指向当前节点)

pNode = pNext;(当前节点指向下一个结点)

循环即可

当pNext == null时,节点达到链表尾部,此时将newHead = pNode;即可得到新链表的头部

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode newHead = null;
        ListNode pNode = head;
        ListNode preNode = null;
        while(pNode != null){
            ListNode pNext = pNode.next;
            if(pNext == null) newHead = pNode;
            pNode.next = preNode;
            preNode = pNode;
            pNode = pNext;
        }
        return newHead;
    }
}

  

 

posted @ 2018-03-10 10:41  SkyeAngel  阅读(139)  评论(0编辑  收藏  举报