您的位置:首页 > 其它

[LeetCode]Reverse Linked List

2014-07-12 15:57 351 查看
顺便练一下普通的reverse linked list

#include <iostream>
using namespace std;

struct ListNode{
int val;
ListNode *next;
ListNode(int x): val(x), next(NULL) {}
};

ListNode *reverse(ListNode *head)
{
if(head == NULL||head->next ==NULL) return head;
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *tail = head;
ListNode *pre = dummy;
ListNode *curr = head;
ListNode *post = head->next;
while(post!= NULL)
{
curr->next = pre;
pre = curr;
curr = post;
post = post->next;
}
curr->next = pre;
tail->next = NULL;
delete dummy;
return curr;
}

int main()
{
ListNode *node1 = new ListNode(3);
ListNode *node2 = new ListNode(5);
ListNode *node3 = new ListNode(6);
ListNode *node4 = new ListNode(7);
node1->next = node2;
node2->next = node3;
node3->next = node4;
ListNode *result = reverse(node1);
ListNode *temp = result;
while(temp!=NULL)
{
cout<<temp->val<<endl temp="temp-">next;
}
return 0;
}

</endl></temp-></iostream>


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.

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
if(head == NULL || head->next == NULL) return head;
//        if(m == n)return head;
ListNode *dummyhead = new ListNode(1);
dummyhead->next = head;
ListNode *pre = dummyhead;
ListNode *curr = head;
ListNode *currnext = head->next;
int i = 1;
while(currnext!= NULL && i<m pre="curr;" curr="curr-">next;
i++;
}
currnext = curr->next;
if(currnext == NULL)
return head;
ListNode *tail1 = pre;
tail1->next = NULL;
ListNode *tail2 = curr;
ListNode *dummy2 = new ListNode(1);
if(tail1 == dummyhead)
tail1 = NULL;
dummy2->next = tail2;
pre = dummy2;
i = m;
while(i<n curr-="">next = pre;
if(currnext != NULL)
{
pre = curr;
curr = currnext;
currnext = currnext->next;
}
i++;
}
curr->next = pre;
dummy2 = NULL;
ListNode *head3;
head3 = currnext;
ListNode *head2;
head2 = curr;
if(tail1 != NULL)
{
tail1->next = head2;
tail2->next = head3;
return head;
}
else
{
tail2->next = head3;
return head2;
}
}
};
</n></m>


在网上还看到一种insert的方法。明天做一下。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode linked list