指针问题与递归问题比较重要。记录几个比较有意思的解法。
三指针反转链表。
public static ListNode reverseList(ListNode head){
if(head == null) return null;
if(head.next == null) return head;
if(head.next.next == null){
ListNode temp = head.next;
head.next = null;
temp.next = head;
return temp;
}
ListNode First = head;
ListNode Second = head.next;
ListNode Third = Second.next;
First.next = null;
while (Third.next != null){
Second.next = First;
First = Second;
Second = Third;
Third = Second.next;
}
Second.next = First;
Third.next = Second;
return Third;
}
递归反转链表。
ListNode alist;
public ListNode reverseList(ListNode head) {
if(head == null){
return null;
}
alist = new ListNode();
ListNode T = alist;
FZ(head);
ListNode l = alist;
while(l != head){
l=l.next;
}
l.next = null;
return T.next;
}
void FZ(ListNode head){
if(head.next == null){
alist.next = head;
alist = alist.next;
return;
}
FZ(head.next);
alist.next = head;
alist = alist.next;
}
其中最后一次反转会产生环,需要注意一下。
- 递归删除链表中的倒数N个节点。
-
public ListNode removeNthFromEnd(ListNode head, int n) { int i = remove(head,n); if(i==n-1){ if(head.next==null){ return null; }else{ return head.next; } } return head; } public int remove(ListNode Head , int lnum){ if(Head.next == null){ return 0; } int num = remove(Head.next,lnum)+1; if(lnum == num){ Head.next = Head.next.next; } return num; }
还有一个回溯算法中的题,单词搜索,这里写一下我的解法。
-
public boolean exist(char[][] board, String word){ ch = board; W = word; for(int y = 0 ; y < board.length ; y++){ for(int x = 0 ; x < board[0].length ; x++){ if (board[y][x] == word.charAt(0)){ it = new int[board.length][board[0].length]; it[y][x] = 1; mymth(x,y,1); } } } return B; } char[][] ch; int [][] it; String W; Boolean B = false; public void mymth(int x ,int y , int index){ if(index == W.length()){ B = true; return; } if(x+1<ch[0].length &&it[y][x+1]==0&& ch[y][x+1] == W.charAt(index)){ it [y][x+1] = 1; mymth(x+1 , y , index+1); it[y][x+1] = 0; } if(x>0 && it[y][x-1] ==0 && ch[y][x-1] == W.charAt(index)){ it [y][x-1] = 1; mymth(x-1 , y , index+1); it[y][x-1] = 0; } if(y+1 <ch.length && it[y+1][x] == 0 && ch[y+1][x] == W.charAt(index)){ it [y+1][x] = 1; mymth(x , y+1 , index+1); it[y+1][x] = 0; } if(y>0 && it[y-1][x] == 0 && ch[y-1][x] == W.charAt(index)){ it [y-1][x] = 1; mymth(x , y-1 , index+1); it[y-1][x] = 0; } }
回溯算法对递归的应用有点难度,要多思考。
-
-