反转链表
问题陈述
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
思路分析
先将结点一个个存入栈,然后逐次弹栈取出。
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class Reverse_LinkList { public ListNode reverseLinklist(ListNode head){ if(head==null||head.next==null) return head; Stack<ListNode> stack=new Stack(); ListNode first=head; while(first!=null){ stack.push(first); first=first.next; } head=stack.pop(); first=head; while (!stack.isEmpty()){ first.next=stack.pop(); first=first.next; } first.next=null; return head;
} public static void main(String[] args){ ListNode head=new ListNode(4); head.next=new ListNode(3); head.next.next=new ListNode(9); Reverse_LinkList reverse_linkList=new Reverse_LinkList(); System.out.println(reverse_linkList.reverseLinklist(head).val); } }
|
双指针迭代
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution{ public ListNode reverselist(ListNode head){ if(head==null||head.next==null) return head; ListNode pre=null; ListNode cur=head; while(cur!=null){ ListNode temp=cur.next; cur.next=pre; cur=temp; pre=cur; } return pre; } }
|