题目描述:html
206:反转链表数据结构
首先想到的是用栈的数据结构来实现反转,由于栈的先进后出特色,咱们能够从头依次将每一个节点压人栈内,再一个个弹出构形成一条新的链表便可。spa
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseList(ListNode head) {
// 建立一个空栈 Stack<Integer> s = new Stack<>(); ListNode res = new ListNode(0); ListNode p = head; ListNode q = res; // 遍历原链表,将节点入栈 while(p != null) { s.push(p.val); p = p.next; } // 节点出栈,构形成新的链表 while(!s.isEmpty()) { q.next = new ListNode(s.pop()); q = q.next; }
// 返回构造后的链表 return res.next; } }
class Solution { public ListNode reverseList(ListNode head) {
// 建立新的节点 ListNode res = null; ListNode next = null;
// p指向头结点 ListNode p = head; while(p != null) { next = p.next; p.next = res; res = p; p = next; } return res; } }
此方法时间效率为O(n),战胜了100%的提交记录。3d
参考资料code