题目要求
反转链表
- 输入一个链表,反转链表后,输出新链表表头
核心思想
类似于C,定义指针进行反转操作。
完整代码如下
/**
* 反转链表
* 输入一个链表,反转链表后,输出新链表表头
*
*/
public class Solution {
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode p = head.next;
ListNode pre = head;
pre.next = null;
ListNode next = p.next;
while(p != null) {
p.next = pre;
pre = p;
p = next;
if(p != null) {
next = p.next;
}
}
head = pre;
return head;
}
}