題目描述
輸入一個鏈表,反轉鏈表後,輸出鏈表的所有元素。
思想:遍歷鏈表,改用頭插法翻轉鏈表。
/*
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){
return null;
}
ListNode newHead = null;//這個一定要爲空,不能爲head,因爲要保證翻轉後鏈表最後一個元素的next=null
ListNode pre = head;
ListNode p;
while(pre!=null){
p = pre.next;
pre.next = newHead;
newHead = pre;
pre = p;
}
return newHead;
}
}
</pre><p></p><p style="font-size:14px; line-height:1.6; margin-bottom:20px; color:rgb(51,51,51); font-family:arial,STHeiti,'Microsoft YaHei',宋體">思想:利用棧,先將鏈表從頭到尾放入棧中,然後從新建立新的鏈表,並輸出。</p><p style="font-size:14px; line-height:1.6; margin-bottom:20px; color:rgb(51,51,51); font-family:arial,STHeiti,'Microsoft YaHei',宋體"></p><pre name="code" class="java">import java.util.Stack;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null){
return null;
}
Stack<Integer> stack = new Stack<Integer>();
ListNode p = head;
while(p!=null){
stack.push(p.val);
p = p.next;
}
ListNode first = new ListNode(stack.pop());
ListNode h = first;
System.out.print(" "+ h.val);
while(!stack.empty()){
ListNode node = new ListNode(stack.pop());
h.next = node;
h = h.next;
System.out.print(" "+ h.val);
}
return first;
}
}