题目分析
输入一个链表,反转链表后,输出链表的所有元素。
代码
/*
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;
}
// 只有一个头结点
if(head.next == null) {
return head;
}
// 定义一个哑结点辅助
ListNode dummy = new ListNode(0);
ListNode temp = head;
while(head != null) {
head = head.next;
temp.next = dummy.next;
dummy.next = temp;
temp = head;
}
return dummy.next;
}
}
网友评论