输入一个链表,反转链表后,输出新链表的表头。
解答:定义一个头结点head,定义一个pre结点为null,定义一个next结点为null。首先让next=head.next;这样保存了head结点下一个结点的信息。然后head.next=pre,让头结点指向了pre结点。然后将指针往后移一位,pre=head,head=next,再继续执行上面操作,最后得到反转的链表。
public class Test15 {
//不需要额外空间
public ListNode ReverseList(ListNode head) {
ListNode pre = null;
ListNode last = null;
ListNode cur = head;
while (cur != null) {
last = cur.next;
cur.next = pre;
pre = cur;
cur = last;
}
return pre;
}
//递归方法
public ListNode ReverseList3(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode temp = head.next;
ListNode newHead = ReverseList3(temp);
temp.next = head;
head.next = null;
return newHead;
}
//需要额外的内存
public ListNode ReverseList2(ListNode head) {
if (head == null) {
return null;
}
ListNode temp = head;
Stack<Integer> stack = new Stack<>();
while (temp != null) {
stack.push(temp.val);
temp = temp.next;
System.out.println(stack);
}
ListNode temp2 = head;
while (temp2 != null) {
System.out.println("1:" + stack);
int value = stack.pop();
temp2.val = value;
temp2 = temp2.next;
System.out.println("2:" + stack);
}
return head;
}
}