Reverse LinkList
描述:反转一个单链表
迭代
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19/***** Definition for linklist *****/
/* typedef struct LNode{
Elemtype data;
struct LNode *next;
* }LNode *linklist
*/
class Solution {
public LNode reverseList(linklist head) {
linklist newhead=null;
linklist now;
while(head!=null){
now=head; //取头
head=head.next; //更新原链头
now.next=newhead; //插入新链
newhead=now; //更新新链头
}
return newhead;
}
}递归
1
2
3
4
5
6
7
8
9class Solution {
public LNode reverseList(linklist head) {
if(head==null||head.next==null)return head;
LNode newhead=reverseList(head.next);
head.next.next=head;
head.next=null;
return newhead;
}
}
LinkedList Cycle
描述:判断一个链表是否有环
1 | /** |
Merge Two Sorted Lists
描述:将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
1 | // 时间复杂度O(min(m,n)) 空间复杂度O(1) |
Remove Nth Node From End of List
描述:给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
1 | //设两个指针p,q,让q先走n步,然后p,q一起走,直到q走到尾结点,删除p->next即可 |
MiddleNode of List
描述:给定一个带有头结点head的非空单链表,返回链表的中间结点。如果,有两个中间结点,则返回第二个中间节点。
1 | //同样使用快慢两个指针,当用慢指针slow遍历列表时,让另一个指针fast的速度是slow的二倍,则当快指针到结尾时,slow指针位于中间。 |