输入一个链表,反转链表后,输出新链表的表头。
给出了用栈实现的方法,实现链表最重要的是不能让表头丢失,否则会报空指针异常的错误。
public class Solution {
public static void main(String[] args) {
//输入一个链表,反转链表后,输出新链表的表头。
ListNode head = new ListNode(1);
ListNode p1 = head;
p1.next = new ListNode(3);
p1 = p1.next;
p1.next = new ListNode(4);
Solution s = new Solution();
System.out.println(s.ReverseList(head));
}
public ListNode ReverseList(ListNode head) {
if(head==null||head.next == null)
{
return head;
}
Stack<Integer> s = new Stack<Integer>();
ListNode l3;
ListNode temp = head; //遍历链表并压栈
while(temp!=null){
s.push(temp.val);
temp=temp.next;
}
System.out.println(s);
l3 = new ListNode(s.peek());
ListNode curr = l3;
s.pop();
while(!s.empty()){
curr.next = new ListNode(s.peek());
curr = curr.next;
s.pop();
}
return l3;
}
}