leetcode 206. Reverse Linked List

算是链表的基本操作的复习。

本地cpp:

#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;

struct p{
	int v;
	p *next;
};
//前插入法 
p* create(vector<int> elem){
	int n=0;
	p *h=NULL,*tem=NULL,*head=NULL;
	h=new p;
	head=h;
	h->v=elem[n];
	h->next=NULL;
	n++;
	while(n<elem.size()){
		tem=new p;
		tem->v=elem[n];
		tem->next=NULL;
		h->next=tem;
		h=tem;
		n++;
	}
	return head; 
}
void showList(p *L){
	while(L!=NULL){
		cout<<L->v<<endl;
		L=L->next;
	}
}
p* reverstList(p *L){
	p *newList,*r,*tem;
	
	r=new p;
	r->v=L->v;
	r->next=NULL;
	
	L=L->next;
	while (L!=NULL){
		tem=new p;
		tem->v=L->v;
		tem->next=r;
		r=tem;
		newList=tem;
		L=L->next;
	}
	return newList;
}
int main()
{
	int b[]={1,2,3,4};
	vector<int> a(b,b+4);
	p *point=create(a);
	showList(point);
	p *pp=reverstList(point);
	showList(pp);
}
 

AC代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* L) {
        if(L==NULL) return NULL;
        ListNode *newList,*r,*tem;

        r=new ListNode(0);
        r->val=L->val;
        r->next=NULL;

        L=L->next;
        while (L!=NULL){
            tem=new ListNode(0);
            tem->val=L->val;
            tem->next=r;
            r=tem;
            newList=tem;
            L=L->next;
        }
        return newList;
    }
};

 

上一篇:【LeetCode每天一题】Swap Nodes in Pairs


下一篇:python学习第四天:基本统计值计算(平均数,方差,中位数)