Reverse a singly linked list.
Hint:
2.迭代
l1表示已经排好倒序的头结点 ;
l2表示后面待倒排链表的头结点
l3=l2.next
3.先遍历得到所有值,然后再重新给链表的节点赋值。
A linked list can be reversed either iteratively or recursively. Could you implement both?
分析:题目要求是实现链表的转置。
用了三种实现:
1.递归
/*递归实现链表转置*/
public ListNode reverseList(ListNode head) {
if(head == null){
return null;
}
ListNode p = head;
if(head.next == null){
return head;
}else{
ListNode list = reverseList(head.next);
p.next.next = p;
p.next = null;/*注意让这个地方最后p指向null*/
return list;
}
}
2.迭代
l1表示已经排好倒序的头结点 ;
l2表示后面待倒排链表的头结点
l3=l2.next
/*迭代做*/
public ListNode reverseList2(ListNode head) {
if(head == null || head.next == null){
return head;
}else{
ListNode l1 = head;
ListNode l2 = l1.next;
l1.next = null;/*注意链表的最后一个元素指向null*/
while(l2.next != null){
ListNode l3 = l2.next;
l2.next = l1;
l1 = l2;
l2 =l3;
}
l2.next = l1;
return l2;
}
}
public ListNode ReverseList2(ListNode head) {
if(head == null){
return head;
}else{
ListNode l1 = null;
ListNode l2 = head;
while(l2.next != null){
ListNode l3 = l2.next;
l2.next = l1;
l1 = l2;
l2 =l3;
}
l2.next = l1;
return l2;
}
}
3.先遍历得到所有值,然后再重新给链表的节点赋值。
<span style="white-space:pre"> </span>/**
* 先遍历得到所有值,然后再重新给链表的节点赋值
*/
public ListNode reverseList3(ListNode head) {
ListNode p = head;
ArrayList vallist = new ArrayList<Integer>();
while(p!=null){
vallist.add(p.val);
p = p.next;
}
p = head;
for(int i=vallist.size()-1;i>=0;i--){
p.val = (int) vallist.get(i);
p =p.next;
}
return head;
}
做链表的题目要重点控制循环的结束条件。