单链表问题(反转、是否有环、删除结尾第N个节点、合并两个sortlist、找到交点)
生活随笔
收集整理的這篇文章主要介紹了
单链表问题(反转、是否有环、删除结尾第N个节点、合并两个sortlist、找到交点)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.時間復雜度O(N),內存O(1)的效率下實現單鏈表的翻轉
public static TreeNode revers(TreeNode head){TreeNode temp,first,second;first=head;second=head.next;while(second!=null){temp=second.next;second.next=first;first=second;second=temp;}head.next=null;head=first;return head;}2.判斷一個鏈表是否存在環,采用的方法是一個指針按照補償為1遍歷,另一個按照步長為2遍歷,如果重合說明有環。
public class IfHasCircle {public static boolean ifhascircle(TreeNode head){TreeNode first=head;TreeNode second=head;while(first!=null && second!=null){if(first==second){return true;}first=first.next;second=second.next.next;}return false;}3.刪除從結尾處數第n個節點。思路是做兩個指針,一個步長比另一個長n,這樣當長的那個節點遍歷到最后一個的時候,就直接把短的節點刪除即可。
public static TreeNode DelTheLastN(TreeNode head,int n){TreeNode first,second;first=head;second=head;for(int i=1;i<=n;i++){second=second.next;}while(second.next!=null){second=second.next;first=first.next;}first.next=first.next.next;return head;}4.合并兩個sort list:用遞歸
static TreeNode mergTwoSortList(TreeNode l1,TreeNode l2){if(l1 == null) return l2;if(l2 == null) return l1;if(l1.val < l2.val) {l1.next = mergTwoSortList(l1.next, l2);return l1;} else {l2.next = mergTwoSortList(l2.next, l1);return l2;}}5. 兩個鏈表相交,找出交點
求出兩個鏈表的長度a和b,一個指針指向較短鏈表的頭head,另一個指針指向較長鏈表的第head+|a-b|,然后兩個指針一起移動,相遇處即為交點。
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) {* val = x;* next = null;* }* }*/ public class Solution {public ListNode getIntersectionNode(ListNode headA, ListNode headB) {if(headA==null || headB==null) return null;int Aindex_length=getLength(headA);int Bindex_length=getLength(headB);int dis=Math.abs(Aindex_length-Bindex_length);ListNode Aindex=headA;ListNode Bindex=headB;if(Aindex_length>=Bindex_length){for(int i=0;i<dis;i++){Aindex=Aindex.next;} while(Bindex!=null){if(Aindex.val==Bindex.val){return Aindex;}else{Aindex=Aindex.next;Bindex=Bindex.next;}}}Aindex=headA;Bindex=headB;if(Aindex_length<Bindex_length){for(int i=0;i<dis;i++){Bindex=Bindex.next;} while(Aindex!=null){if(Aindex.val==Bindex.val){return Aindex;}else{Aindex=Aindex.next;Bindex=Bindex.next;}}}return null;}public int getLength(ListNode head){ListNode index=head;int length=1;while(index.next!=null){index=index.next;length++;}return length;} }
/********************************
* 本文來自博客 ?“李博Garvin“
* 轉載請標明出處:http://blog.csdn.net/buptgshengod
******************************************/
總結
以上是生活随笔為你收集整理的单链表问题(反转、是否有环、删除结尾第N个节点、合并两个sortlist、找到交点)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面试总结-百度(1)
- 下一篇: 【LeetCode从零单排】No121B