1、Reverse Linked List
Reverse a singly linked list.
翻转一个单链表且只可移动节点,不改变节点的值。
思路大概就是,将头节点后一节点移到最前面,直到头节点后面没有节点了,就完成了翻转。
由于要移到最前面就要有个指针指向这个位置,于是新定义一个节点,使其一直指向链表的最前面节点。
过程大概如下图:
图中pre,cur指针都指向固定节点,temp指针指向固定位置,即pre->next。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode dummy(-1);
ListNode* pre=&dummy;
pre->next=head;
ListNode* cur=head;
while(cur&&cur->next){
ListNode* temp=pre->next;
pre->next=cur->next;
cur->next=cur->next->next;
pre->next->next=temp;
}
return dummy.next;
}
};
学到一种新的反转,简单粗暴的把箭头都反过来了,值得推荐~~
ListNode* reverseList(ListNode* head){
ListNode* newhead=NULL;
ListNode* pre=NUll;
ListNOde* cur=head;
while(cur!=NULL){
ListNode* next=cur->next;
if(cur->next=NULL)
newhead=cur;
cur->next=pre;
pre=cur;
cur=next;
}
return new head;
}
2、Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
嗯~~跟上面一模一样的道理哦~~就是把第m个节点当成head,第n个节点当成尾节点就好啦~~
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode dummy(-1);
dummy.next=head;
ListNode *pre=&dummy;
for(int i=0;i<m-1;i++){
pre=pre->next; //m-1
}
ListNode* const cur=pre->next;//m
for(int i=m;i<n;i++){
ListNode* temp=pre->next;
pre->next=cur->next;
cur->next=pre->next->next;
pre->next->next=temp;
}
return dummy.next;
}
};
每次新建一个指针都会降低效率,下面这种方法道理也是一样,不过……0ms!!!
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode dummy(0);
dummy.next=head;
ListNode *pre=&dummy;
for(int i=0;i<m-1;i++){
pre=pre->next;
}
ListNode* const head2=pre;//m-1
pre=head2->next;//m
ListNode *cur=pre->next;//m+1
for(int i=m;i<n;i++){
pre->next=cur->next;
cur->next=head2->next;
head2->next=cur;
cur=pre->next;
}
return dummy.next;
}
};
3、Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
每两个交换一下,其实道理也是一样~
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode dummy(-1);
ListNode* pre=&dummy;
pre->next=head;
ListNode* cur=head;
while(cur&&cur->next){
pre->next=cur->next;
cur->next=pre->next->next;
pre->next->next=cur;
cur=cur->next;
pre=pre->next->next;
}
return dummy.next;
}
};