题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
第一种方法是用了栈的先入后出的思想来反转链表。
/*
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 head;
}
//使用list来充当栈
ArrayList<ListNode> stack = new ArrayList();
while(head != null){
stack.add(0, head);
head = head.next;
}
//保留最终返回的头结点
ListNode rtHead = stack.get(0);
ListNode node = rtHead;
//出栈,按顺序设置节点
for(int i = 1; i < stack.size(); i++){
node.next = stack.get(i);
node = node.next;
}
//末尾节点的next设置为空
node.next = null;
return rtHead;
}
}
1.先保存当前节点的next节点。
2.将当前节点的next指针指向pre节点。
3.将当前节点设置为pre节点。
4.继续遍历下一个节点(用1里面保存的节点);
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode pre = null;
ListNode nxt = null;
while(head != null){
//1.首先保留next节点
nxt = head.next;
//2.将当前节点的next指向上一个节点(反转)
head.next = pre;
//3.当前节点对于下一个节点来说也是pre节点
pre = head;
//4.指针顺移
head = nxt;
}
//while的退出条件是head == null,所以返回当前节点的pre则是反转后的头结点
return pre;
}
}
格力公司福利 248人发布