Reverse Linked List II--LeetCode

题目:

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ? m ? n ? length of list.

思路:由于要求one-pass,这里就不能使用简单化的操作了,如果没有这个要求,我们可以找到m到n的这段链表,然后进行反转,然后标记链接即可。有这个要求之后就必须在M到n之间进行转换。尤其注意从第一个节点开始反转

#include <iostream> 
#include <vector>
#include <string>
using namespace std;
typedef struct list_node List;  
struct list_node  
{  
    struct list_node* next;  
    int value;  
};  
  
void print_list(List* list)  
{  
    List* tmp=list;  
    while(tmp != NULL)  
    {  
        cout<<tmp->value<<endl;  
        tmp = tmp->next;   
    }  
}  
  
/* 
初始化List  将从1~n的数字插入到链表中  
*/  
void Init_List(List*& head,int* array,int n)  
{  
    head = NULL;  
    List* tmp;  
    List* record;  
       
    for(int i=1;i<=n;i++)  
    {  
        tmp = new List;  
        tmp->next = NULL;  
        tmp->value = array[i-1];  
        if(head == NULL)  
        {  
            head = tmp;  
            record = head;  
        }  
        else  
        {  
            record->next = tmp;  
            record = tmp;  
        }  
    }  
}  
  
int Len_list(List* list)  
{  
    if(list == NULL)  
        return 0;  
    else  
        return Len_list(list->next)+1;  
}  

// 将链表中的第m个节点到第n个节点之间的元素进行反转 
void ReverseList(List*& list,int m,int n)  
{
		if(list == NULL || list->next == NULL || n-m<=1) 
			return ;
		int num=1;
		List* pre,*next,*cur,*tmp,*temp;
		cur= list;
		pre = NULL;
		while(cur != NULL)
		{
			next = cur->next;
			if(num < m)
			{
				pre = cur;
				cur = next;
			}
			if(num == m)
			{
				tmp = cur;
				temp = cur;
				cur = next;			 
			}
				
			if(num >m && num <= n)
			{
				cur->next = temp;
				temp = cur;
				cur = next;			 
			}
			if(num == n)
			{
				if(m ==1)
					list = temp;
				else
					pre->next = temp;					
				tmp->next = cur;
				break;
			}
			num++;
		}
} 

int main() 
{
	int array[]={5,1,2,7,8,4,3,6,10,9};
	//int array[]={1,4,3,2,5,2};
	List* list;
	Init_List(list,array,sizeof(array)/sizeof(int));
	ReverseList(list,1,3);
	print_list(list);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值