反转链表(面试笔试高频考点)
题目描述
输入一个链表,反转链表后,输出新链表的表头。
思路
定义两个指针,反向输出
/*
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 pre = null;
while(head != null){
ListNode temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
return pre;
}
}
//方法二
/*
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 pre = null;
ListNode next = null;
while(head != null){ //注意这个地方的写法,如果写head.next将会丢失最后一个节点
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}