赞
踩
题目链接如下:点击跳转
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路一: 栈
思路二: 递归
temp.next.next == null;
这样就实现了将倒数第二个节点设为了出口倒数第一个节点
指向倒数第二个节点
,将原先倒数第二个节点
指向倒数第一个节点
的指向拆除 temp.next.next = temp;
temp.next = null;
思路三: 头插法
思路四: 迭代
class Solution { public ListNode reverseList(ListNode head) { LinkedList<ListNode> stack = new LinkedList<ListNode>(); while(head != null){ stack.addLast(head); head = head.next; } ListNode cur = null; if(!stack.isEmpty()){ cur = stack.removeLast(); head = cur; } while(!stack.isEmpty()){ ListNode next = stack.removeLast(); cur.next = next; next.next = null; cur = next; } return head; } }
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
class Solution { public ListNode reverseList(ListNode head) { if(head==null){ return head; } ListNode newLast = head; ListNode cur = head.next; newLast.next = null; while(cur != null){ ListNode temp = cur.next; cur.next = newLast; newLast = cur; cur = temp; } return newLast; } }
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){
return head;
}
ListNode pre = null;
while(head != null){
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
问题得以解决,如有更好思路欢迎评论,私聊。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。