题目描述
输入一个链表,反转链表后,输出新链表的表头。
解题方法
1.使用一个栈,将链表的元素放入栈后取出,完成反转。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.*;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null)
return null;
Stack<Integer> temp = new Stack<Integer>();
ListNode p =head;
ListNode q = head; //头结点
while(p!=null)
{
temp.push(p.val);
p = p.next;
}
while(!temp.empty())
{
head.val = temp.pop();
head = head.next;
}
return q;
}
}
2.类似使用两个指针,正常反转。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.*;
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode pre = null;
ListNode next = null;
while(head!=null)
{
pre = head;
head = head.next;
pre.next = next;
next = pre;
}
return next;
}
}